id
int64 4
16.3M
| file_name
stringlengths 3
68
| file_path
stringlengths 14
181
| content
stringlengths 39
9.06M
| size
int64 39
9.06M
| language
stringclasses 1
value | extension
stringclasses 2
values | total_lines
int64 1
711k
| avg_line_length
float64 3.18
138
| max_line_length
int64 10
140
| alphanum_fraction
float64 0.02
0.93
| repo_name
stringlengths 7
69
| repo_stars
int64 2
61.6k
| repo_forks
int64 12
7.81k
| repo_open_issues
int64 0
1.13k
| repo_license
stringclasses 10
values | repo_extraction_date
stringclasses 657
values | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 1
class | exact_duplicates_redpajama
bool 1
class | exact_duplicates_githubcode
bool 2
classes | near_duplicates_stackv2
bool 1
class | near_duplicates_stackv1
bool 1
class | near_duplicates_redpajama
bool 1
class | near_duplicates_githubcode
bool 2
classes |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
747 |
ventoy_json.c
|
ventoy_Ventoy/LinuxGUI/Ventoy2Disk/Core/ventoy_json.c
|
/******************************************************************************
* ventoy_json.c
*
* Copyright (c) 2021, longpanda <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <linux/limits.h>
#include <ventoy_define.h>
#include <ventoy_util.h>
#include <ventoy_json.h>
static void vtoy_json_free(VTOY_JSON *pstJsonHead)
{
VTOY_JSON *pstNext = NULL;
while (NULL != pstJsonHead)
{
pstNext = pstJsonHead->pstNext;
if ((pstJsonHead->enDataType < JSON_TYPE_BUTT) && (NULL != pstJsonHead->pstChild))
{
vtoy_json_free(pstJsonHead->pstChild);
}
free(pstJsonHead);
pstJsonHead = pstNext;
}
return;
}
static char *vtoy_json_skip(const char *pcData)
{
while ((NULL != pcData) && ('\0' != *pcData) && (*pcData <= 32))
{
pcData++;
}
return (char *)pcData;
}
VTOY_JSON *vtoy_json_find_item
(
VTOY_JSON *pstJson,
JSON_TYPE enDataType,
const char *szKey
)
{
while (NULL != pstJson)
{
if ((enDataType == pstJson->enDataType) &&
(0 == strcmp(szKey, pstJson->pcName)))
{
return pstJson;
}
pstJson = pstJson->pstNext;
}
return NULL;
}
static int vtoy_json_parse_number
(
VTOY_JSON *pstJson,
const char *pcData,
const char **ppcEnd
)
{
unsigned long Value;
Value = strtoul(pcData, (char **)ppcEnd, 10);
if (*ppcEnd == pcData)
{
vdebug("Failed to parse json number %s.\n", pcData);
return JSON_FAILED;
}
pstJson->enDataType = JSON_TYPE_NUMBER;
pstJson->unData.lValue = Value;
return JSON_SUCCESS;
}
static int vtoy_json_parse_string
(
char *pcNewStart,
char *pcRawStart,
VTOY_JSON *pstJson,
const char *pcData,
const char **ppcEnd
)
{
uint32_t uiLen = 0;
const char *pcPos = NULL;
const char *pcTmp = pcData + 1;
*ppcEnd = pcData;
if ('\"' != *pcData)
{
return JSON_FAILED;
}
pcPos = strchr(pcTmp, '\"');
if ((NULL == pcPos) || (pcPos < pcTmp))
{
vdebug("Invalid string %s.\n", pcData);
return JSON_FAILED;
}
*ppcEnd = pcPos + 1;
uiLen = (uint32_t)(unsigned long)(pcPos - pcTmp);
pstJson->enDataType = JSON_TYPE_STRING;
pstJson->unData.pcStrVal = pcNewStart + (pcTmp - pcRawStart);
pstJson->unData.pcStrVal[uiLen] = '\0';
return JSON_SUCCESS;
}
static int vtoy_json_parse_array
(
char *pcNewStart,
char *pcRawStart,
VTOY_JSON *pstJson,
const char *pcData,
const char **ppcEnd
)
{
int Ret = JSON_SUCCESS;
VTOY_JSON *pstJsonChild = NULL;
VTOY_JSON *pstJsonItem = NULL;
const char *pcTmp = pcData + 1;
*ppcEnd = pcData;
pstJson->enDataType = JSON_TYPE_ARRAY;
if ('[' != *pcData)
{
return JSON_FAILED;
}
pcTmp = vtoy_json_skip(pcTmp);
if (']' == *pcTmp)
{
*ppcEnd = pcTmp + 1;
return JSON_SUCCESS;
}
JSON_NEW_ITEM(pstJson->pstChild, JSON_FAILED);
Ret = vtoy_json_parse_value(pcNewStart, pcRawStart, pstJson->pstChild, pcTmp, ppcEnd);
if (JSON_SUCCESS != Ret)
{
vdebug("Failed to parse array child.\n");
return JSON_FAILED;
}
pstJsonChild = pstJson->pstChild;
pcTmp = vtoy_json_skip(*ppcEnd);
while ((NULL != pcTmp) && (',' == *pcTmp))
{
JSON_NEW_ITEM(pstJsonItem, JSON_FAILED);
pstJsonChild->pstNext = pstJsonItem;
pstJsonItem->pstPrev = pstJsonChild;
pstJsonChild = pstJsonItem;
Ret = vtoy_json_parse_value(pcNewStart, pcRawStart, pstJsonChild, vtoy_json_skip(pcTmp + 1), ppcEnd);
if (JSON_SUCCESS != Ret)
{
vdebug("Failed to parse array child.\n");
return JSON_FAILED;
}
pcTmp = vtoy_json_skip(*ppcEnd);
}
if ((NULL != pcTmp) && (']' == *pcTmp))
{
*ppcEnd = pcTmp + 1;
return JSON_SUCCESS;
}
else
{
*ppcEnd = pcTmp;
return JSON_FAILED;
}
}
static int vtoy_json_parse_object
(
char *pcNewStart,
char *pcRawStart,
VTOY_JSON *pstJson,
const char *pcData,
const char **ppcEnd
)
{
int Ret = JSON_SUCCESS;
VTOY_JSON *pstJsonChild = NULL;
VTOY_JSON *pstJsonItem = NULL;
const char *pcTmp = pcData + 1;
*ppcEnd = pcData;
pstJson->enDataType = JSON_TYPE_OBJECT;
if ('{' != *pcData)
{
return JSON_FAILED;
}
pcTmp = vtoy_json_skip(pcTmp);
if ('}' == *pcTmp)
{
*ppcEnd = pcTmp + 1;
return JSON_SUCCESS;
}
JSON_NEW_ITEM(pstJson->pstChild, JSON_FAILED);
Ret = vtoy_json_parse_string(pcNewStart, pcRawStart, pstJson->pstChild, pcTmp, ppcEnd);
if (JSON_SUCCESS != Ret)
{
vdebug("Failed to parse array child.\n");
return JSON_FAILED;
}
pstJsonChild = pstJson->pstChild;
pstJsonChild->pcName = pstJsonChild->unData.pcStrVal;
pstJsonChild->unData.pcStrVal = NULL;
pcTmp = vtoy_json_skip(*ppcEnd);
if ((NULL == pcTmp) || (':' != *pcTmp))
{
*ppcEnd = pcTmp;
return JSON_FAILED;
}
Ret = vtoy_json_parse_value(pcNewStart, pcRawStart, pstJsonChild, vtoy_json_skip(pcTmp + 1), ppcEnd);
if (JSON_SUCCESS != Ret)
{
vdebug("Failed to parse array child.\n");
return JSON_FAILED;
}
pcTmp = vtoy_json_skip(*ppcEnd);
while ((NULL != pcTmp) && (',' == *pcTmp))
{
JSON_NEW_ITEM(pstJsonItem, JSON_FAILED);
pstJsonChild->pstNext = pstJsonItem;
pstJsonItem->pstPrev = pstJsonChild;
pstJsonChild = pstJsonItem;
Ret = vtoy_json_parse_string(pcNewStart, pcRawStart, pstJsonChild, vtoy_json_skip(pcTmp + 1), ppcEnd);
if (JSON_SUCCESS != Ret)
{
vdebug("Failed to parse array child.\n");
return JSON_FAILED;
}
pcTmp = vtoy_json_skip(*ppcEnd);
pstJsonChild->pcName = pstJsonChild->unData.pcStrVal;
pstJsonChild->unData.pcStrVal = NULL;
if ((NULL == pcTmp) || (':' != *pcTmp))
{
*ppcEnd = pcTmp;
return JSON_FAILED;
}
Ret = vtoy_json_parse_value(pcNewStart, pcRawStart, pstJsonChild, vtoy_json_skip(pcTmp + 1), ppcEnd);
if (JSON_SUCCESS != Ret)
{
vdebug("Failed to parse array child.\n");
return JSON_FAILED;
}
pcTmp = vtoy_json_skip(*ppcEnd);
}
if ((NULL != pcTmp) && ('}' == *pcTmp))
{
*ppcEnd = pcTmp + 1;
return JSON_SUCCESS;
}
else
{
*ppcEnd = pcTmp;
return JSON_FAILED;
}
}
int vtoy_json_parse_value
(
char *pcNewStart,
char *pcRawStart,
VTOY_JSON *pstJson,
const char *pcData,
const char **ppcEnd
)
{
pcData = vtoy_json_skip(pcData);
switch (*pcData)
{
case 'n':
{
if (0 == strncmp(pcData, "null", 4))
{
pstJson->enDataType = JSON_TYPE_NULL;
*ppcEnd = pcData + 4;
return JSON_SUCCESS;
}
break;
}
case 'f':
{
if (0 == strncmp(pcData, "false", 5))
{
pstJson->enDataType = JSON_TYPE_BOOL;
pstJson->unData.lValue = 0;
*ppcEnd = pcData + 5;
return JSON_SUCCESS;
}
break;
}
case 't':
{
if (0 == strncmp(pcData, "true", 4))
{
pstJson->enDataType = JSON_TYPE_BOOL;
pstJson->unData.lValue = 1;
*ppcEnd = pcData + 4;
return JSON_SUCCESS;
}
break;
}
case '\"':
{
return vtoy_json_parse_string(pcNewStart, pcRawStart, pstJson, pcData, ppcEnd);
}
case '[':
{
return vtoy_json_parse_array(pcNewStart, pcRawStart, pstJson, pcData, ppcEnd);
}
case '{':
{
return vtoy_json_parse_object(pcNewStart, pcRawStart, pstJson, pcData, ppcEnd);
}
case '-':
{
return vtoy_json_parse_number(pstJson, pcData, ppcEnd);
}
default :
{
if (*pcData >= '0' && *pcData <= '9')
{
return vtoy_json_parse_number(pstJson, pcData, ppcEnd);
}
}
}
*ppcEnd = pcData;
vdebug("Invalid json data %u.\n", (uint8_t)(*pcData));
return JSON_FAILED;
}
VTOY_JSON * vtoy_json_create(void)
{
VTOY_JSON *pstJson = NULL;
pstJson = (VTOY_JSON *)zalloc(sizeof(VTOY_JSON));
if (NULL == pstJson)
{
return NULL;
}
return pstJson;
}
int vtoy_json_parse(VTOY_JSON *pstJson, const char *szJsonData)
{
uint32_t uiMemSize = 0;
int Ret = JSON_SUCCESS;
char *pcNewBuf = NULL;
const char *pcEnd = NULL;
uiMemSize = strlen(szJsonData) + 1;
pcNewBuf = (char *)malloc(uiMemSize);
if (NULL == pcNewBuf)
{
vdebug("Failed to alloc new buf.\n");
return JSON_FAILED;
}
memcpy(pcNewBuf, szJsonData, uiMemSize);
pcNewBuf[uiMemSize - 1] = 0;
Ret = vtoy_json_parse_value(pcNewBuf, (char *)szJsonData, pstJson, szJsonData, &pcEnd);
if (JSON_SUCCESS != Ret)
{
vdebug("Failed to parse json data %s start=%p, end=%p:%s.\n",
szJsonData, szJsonData, pcEnd, pcEnd);
return JSON_FAILED;
}
return JSON_SUCCESS;
}
int vtoy_json_scan_parse
(
const VTOY_JSON *pstJson,
uint32_t uiParseNum,
VTOY_JSON_PARSE_S *pstJsonParse
)
{
uint32_t i = 0;
const VTOY_JSON *pstJsonCur = NULL;
VTOY_JSON_PARSE_S *pstCurParse = NULL;
for (pstJsonCur = pstJson; NULL != pstJsonCur; pstJsonCur = pstJsonCur->pstNext)
{
if ((JSON_TYPE_OBJECT == pstJsonCur->enDataType) ||
(JSON_TYPE_ARRAY == pstJsonCur->enDataType))
{
continue;
}
for (i = 0, pstCurParse = NULL; i < uiParseNum; i++)
{
if (0 == strcmp(pstJsonParse[i].pcKey, pstJsonCur->pcName))
{
pstCurParse = pstJsonParse + i;
break;
}
}
if (NULL == pstCurParse)
{
continue;
}
switch (pstJsonCur->enDataType)
{
case JSON_TYPE_NUMBER:
{
if (sizeof(uint32_t) == pstCurParse->uiBufSize)
{
*(uint32_t *)(pstCurParse->pDataBuf) = (uint32_t)pstJsonCur->unData.lValue;
}
else if (sizeof(uint16_t) == pstCurParse->uiBufSize)
{
*(uint16_t *)(pstCurParse->pDataBuf) = (uint16_t)pstJsonCur->unData.lValue;
}
else if (sizeof(uint8_t) == pstCurParse->uiBufSize)
{
*(uint8_t *)(pstCurParse->pDataBuf) = (uint8_t)pstJsonCur->unData.lValue;
}
else if ((pstCurParse->uiBufSize > sizeof(uint64_t)))
{
snprintf((char *)pstCurParse->pDataBuf, pstCurParse->uiBufSize, "%llu",
(unsigned long long)(pstJsonCur->unData.lValue));
}
else
{
vdebug("Invalid number data buf size %u.\n", pstCurParse->uiBufSize);
}
break;
}
case JSON_TYPE_STRING:
{
strncpy((char *)pstCurParse->pDataBuf, pstJsonCur->unData.pcStrVal, pstCurParse->uiBufSize);
break;
}
case JSON_TYPE_BOOL:
{
*(uint8_t *)(pstCurParse->pDataBuf) = (pstJsonCur->unData.lValue) > 0 ? 1 : 0;
break;
}
default :
{
break;
}
}
}
return JSON_SUCCESS;
}
int vtoy_json_scan_array
(
VTOY_JSON *pstJson,
const char *szKey,
VTOY_JSON **ppstArrayItem
)
{
VTOY_JSON *pstJsonItem = NULL;
pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_ARRAY, szKey);
if (NULL == pstJsonItem)
{
vdebug("Key %s is not found in json data.\n", szKey);
return JSON_NOT_FOUND;
}
*ppstArrayItem = pstJsonItem;
return JSON_SUCCESS;
}
int vtoy_json_scan_array_ex
(
VTOY_JSON *pstJson,
const char *szKey,
VTOY_JSON **ppstArrayItem
)
{
VTOY_JSON *pstJsonItem = NULL;
pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_ARRAY, szKey);
if (NULL == pstJsonItem)
{
vdebug("Key %s is not found in json data.\n", szKey);
return JSON_NOT_FOUND;
}
*ppstArrayItem = pstJsonItem->pstChild;
return JSON_SUCCESS;
}
int vtoy_json_scan_object
(
VTOY_JSON *pstJson,
const char *szKey,
VTOY_JSON **ppstObjectItem
)
{
VTOY_JSON *pstJsonItem = NULL;
pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_OBJECT, szKey);
if (NULL == pstJsonItem)
{
vdebug("Key %s is not found in json data.\n", szKey);
return JSON_NOT_FOUND;
}
*ppstObjectItem = pstJsonItem;
return JSON_SUCCESS;
}
int vtoy_json_get_int
(
VTOY_JSON *pstJson,
const char *szKey,
int *piValue
)
{
VTOY_JSON *pstJsonItem = NULL;
pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_NUMBER, szKey);
if (NULL == pstJsonItem)
{
vdebug("Key %s is not found in json data.\n", szKey);
return JSON_NOT_FOUND;
}
*piValue = (int)pstJsonItem->unData.lValue;
return JSON_SUCCESS;
}
int vtoy_json_get_uint
(
VTOY_JSON *pstJson,
const char *szKey,
uint32_t *puiValue
)
{
VTOY_JSON *pstJsonItem = NULL;
pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_NUMBER, szKey);
if (NULL == pstJsonItem)
{
vdebug("Key %s is not found in json data.\n", szKey);
return JSON_NOT_FOUND;
}
*puiValue = (uint32_t)pstJsonItem->unData.lValue;
return JSON_SUCCESS;
}
int vtoy_json_get_uint64
(
VTOY_JSON *pstJson,
const char *szKey,
uint64_t *pui64Value
)
{
VTOY_JSON *pstJsonItem = NULL;
pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_NUMBER, szKey);
if (NULL == pstJsonItem)
{
vdebug("Key %s is not found in json data.\n", szKey);
return JSON_NOT_FOUND;
}
*pui64Value = (uint64_t)pstJsonItem->unData.lValue;
return JSON_SUCCESS;
}
int vtoy_json_get_bool
(
VTOY_JSON *pstJson,
const char *szKey,
uint8_t *pbValue
)
{
VTOY_JSON *pstJsonItem = NULL;
pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_BOOL, szKey);
if (NULL == pstJsonItem)
{
vdebug("Key %s is not found in json data.\n", szKey);
return JSON_NOT_FOUND;
}
*pbValue = pstJsonItem->unData.lValue > 0 ? 1 : 0;
return JSON_SUCCESS;
}
int vtoy_json_get_string
(
VTOY_JSON *pstJson,
const char *szKey,
uint32_t uiBufLen,
char *pcBuf
)
{
VTOY_JSON *pstJsonItem = NULL;
pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_STRING, szKey);
if (NULL == pstJsonItem)
{
vdebug("Key %s is not found in json data.\n", szKey);
return JSON_NOT_FOUND;
}
strncpy(pcBuf, pstJsonItem->unData.pcStrVal, uiBufLen);
return JSON_SUCCESS;
}
const char * vtoy_json_get_string_ex(VTOY_JSON *pstJson, const char *szKey)
{
VTOY_JSON *pstJsonItem = NULL;
if ((NULL == pstJson) || (NULL == szKey))
{
return NULL;
}
pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_STRING, szKey);
if (NULL == pstJsonItem)
{
vdebug("Key %s is not found in json data.\n", szKey);
return NULL;
}
return pstJsonItem->unData.pcStrVal;
}
int vtoy_json_destroy(VTOY_JSON *pstJson)
{
if (NULL == pstJson)
{
return JSON_SUCCESS;
}
if (NULL != pstJson->pstChild)
{
vtoy_json_free(pstJson->pstChild);
}
if (NULL != pstJson->pstNext)
{
vtoy_json_free(pstJson->pstNext);
}
free(pstJson);
return JSON_SUCCESS;
}
| 17,775 |
C
|
.c
| 615 | 20.81626 | 111 | 0.55395 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
748 |
ventoy_util.c
|
ventoy_Ventoy/LinuxGUI/Ventoy2Disk/Core/ventoy_util.c
|
/******************************************************************************
* ventoy_util.c ---- ventoy util
* Copyright (c) 2021, longpanda <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mount.h>
#include <linux/fs.h>
#include <dirent.h>
#include <time.h>
#include <ventoy_define.h>
#include <ventoy_util.h>
uint8_t g_mbr_template[512];
void ventoy_gen_preudo_uuid(void *uuid)
{
int i;
int fd;
fd = open("/dev/urandom", O_RDONLY | O_BINARY);
if (fd < 0)
{
srand(time(NULL));
for (i = 0; i < 8; i++)
{
*((uint16_t *)uuid + i) = (uint16_t)(rand() & 0xFFFF);
}
}
else
{
read(fd, uuid, 16);
close(fd);
}
}
uint64_t ventoy_get_human_readable_gb(uint64_t SizeBytes)
{
int i;
int Pow2 = 1;
double Delta;
double GB = SizeBytes * 1.0 / 1000 / 1000 / 1000;
if ((SizeBytes % SIZE_1GB) == 0)
{
return (uint64_t)(SizeBytes / SIZE_1GB);
}
for (i = 0; i < 12; i++)
{
if (Pow2 > GB)
{
Delta = (Pow2 - GB) / Pow2;
}
else
{
Delta = (GB - Pow2) / Pow2;
}
if (Delta < 0.05)
{
return Pow2;
}
Pow2 <<= 1;
}
return (uint64_t)GB;
}
int ventoy_get_sys_file_line(char *buffer, int buflen, const char *fmt, ...)
{
int len;
char c;
char path[256];
va_list arg;
va_start(arg, fmt);
vsnprintf(path, 256, fmt, arg);
va_end(arg);
if (access(path, F_OK) >= 0)
{
FILE *fp = fopen(path, "r");
memset(buffer, 0, buflen);
len = (int)fread(buffer, 1, buflen - 1, fp);
fclose(fp);
while (len > 0)
{
c = buffer[len - 1];
if (c == '\r' || c == '\n' || c == ' ' || c == '\t')
{
buffer[len - 1] = 0;
len--;
}
else
{
break;
}
}
return 0;
}
else
{
vdebug("%s not exist \n", path);
return 1;
}
}
int ventoy_is_disk_mounted(const char *devpath)
{
int len;
int mount = 0;
char line[512];
FILE *fp = NULL;
fp = fopen("/proc/mounts", "r");
if (!fp)
{
return 0;
}
len = (int)strlen(devpath);
while (fgets(line, sizeof(line), fp))
{
if (strncmp(line, devpath, len) == 0)
{
mount = 1;
vdebug("%s mounted <%s>\n", devpath, line);
goto end;
}
}
end:
fclose(fp);
return mount;
}
static int ventoy_mount_path_escape(char *src, char *dst, int len)
{
int i = 0;
int n = 0;
dst[len - 1] = 0;
for (i = 0; i < len - 1; i++)
{
if (src[i] == '\\' && src[i + 1] == '0' && src[i + 2] == '4' && src[i + 3] == '0')
{
dst[n++] = ' ';
i += 3;
}
else
{
dst[n++] = src[i];
}
if (src[i] == 0)
{
break;
}
}
return 0;
}
int ventoy_try_umount_disk(const char *devpath)
{
int rc;
int len;
char line[1024];
char mntpt[1024];
char *pos1 = NULL;
char *pos2 = NULL;
FILE *fp = NULL;
fp = fopen("/proc/mounts", "r");
if (!fp)
{
return 0;
}
len = (int)strlen(devpath);
while (fgets(line, sizeof(line), fp))
{
if (strncmp(line, devpath, len) == 0)
{
pos1 = strchr(line, ' ');
if (pos1)
{
pos2 = strchr(pos1 + 1, ' ');
if (pos2)
{
*pos2 = 0;
}
ventoy_mount_path_escape(pos1 + 1, mntpt, sizeof(mntpt));
rc = umount(mntpt);
if (rc)
{
vdebug("umount <%s> <%s> [ failed ] error:%d\n", devpath, mntpt, errno);
}
else
{
vdebug("umount <%s> <%s> [ success ]\n", devpath, mntpt);
}
}
}
}
fclose(fp);
return 0;
}
int ventoy_read_file_to_buf(const char *FileName, int ExtLen, void **Bufer, int *BufLen)
{
int FileSize;
FILE *fp = NULL;
void *Data = NULL;
fp = fopen(FileName, "rb");
if (fp == NULL)
{
vlog("Failed to open file %s", FileName);
return 1;
}
fseek(fp, 0, SEEK_END);
FileSize = (int)ftell(fp);
Data = malloc(FileSize + ExtLen);
if (!Data)
{
fclose(fp);
return 1;
}
fseek(fp, 0, SEEK_SET);
fread(Data, 1, FileSize, fp);
fclose(fp);
*Bufer = Data;
*BufLen = FileSize;
return 0;
}
const char * ventoy_get_local_version(void)
{
int rc;
int FileSize;
char *Pos = NULL;
char *Buf = NULL;
static char LocalVersion[64] = { 0 };
if (LocalVersion[0] == 0)
{
rc = ventoy_read_file_to_buf("ventoy/version", 1, (void **)&Buf, &FileSize);
if (rc)
{
return "";
}
Buf[FileSize] = 0;
for (Pos = Buf; *Pos; Pos++)
{
if (*Pos == '\r' || *Pos == '\n')
{
*Pos = 0;
break;
}
}
scnprintf(LocalVersion, "%s", Buf);
free(Buf);
}
return LocalVersion;
}
int VentoyGetLocalBootImg(MBR_HEAD *pMBR)
{
memcpy(pMBR, g_mbr_template, 512);
return 0;
}
static int VentoyFillProtectMBR(uint64_t DiskSizeBytes, MBR_HEAD *pMBR)
{
ventoy_guid Guid;
uint32_t DiskSignature;
uint64_t DiskSectorCount;
VentoyGetLocalBootImg(pMBR);
ventoy_gen_preudo_uuid(&Guid);
memcpy(&DiskSignature, &Guid, sizeof(uint32_t));
vdebug("Disk signature: 0x%08x\n", DiskSignature);
memcpy(pMBR->BootCode + 0x1B8, &DiskSignature, 4);
memcpy(pMBR->BootCode + 0x180, &Guid, 16);
DiskSectorCount = DiskSizeBytes / 512 - 1;
if (DiskSectorCount > 0xFFFFFFFF)
{
DiskSectorCount = 0xFFFFFFFF;
}
memset(pMBR->PartTbl, 0, sizeof(pMBR->PartTbl));
pMBR->PartTbl[0].Active = 0x00;
pMBR->PartTbl[0].FsFlag = 0xee; // EE
pMBR->PartTbl[0].StartHead = 0;
pMBR->PartTbl[0].StartSector = 1;
pMBR->PartTbl[0].StartCylinder = 0;
pMBR->PartTbl[0].EndHead = 254;
pMBR->PartTbl[0].EndSector = 63;
pMBR->PartTbl[0].EndCylinder = 1023;
pMBR->PartTbl[0].StartSectorId = 1;
pMBR->PartTbl[0].SectorCount = (uint32_t)DiskSectorCount;
pMBR->Byte55 = 0x55;
pMBR->ByteAA = 0xAA;
pMBR->BootCode[92] = 0x22;
return 0;
}
static int ventoy_fill_gpt_partname(uint16_t Name[36], const char *asciiName)
{
int i;
int len;
memset(Name, 0, 36 * sizeof(uint16_t));
len = (int)strlen(asciiName);
for (i = 0; i < 36 && i < len; i++)
{
Name[i] = asciiName[i];
}
return 0;
}
int ventoy_fill_gpt(uint64_t size, uint64_t reserve, int align4k, VTOY_GPT_INFO *gpt)
{
uint64_t ReservedSector = 33;
uint64_t ModSectorCount = 0;
uint64_t Part1SectorCount = 0;
uint64_t DiskSectorCount = size / 512;
VTOY_GPT_HDR *Head = &gpt->Head;
VTOY_GPT_PART_TBL *Table = gpt->PartTbl;
ventoy_guid WindowsDataPartType = { 0xebd0a0a2, 0xb9e5, 0x4433, { 0x87, 0xc0, 0x68, 0xb6, 0xb7, 0x26, 0x99, 0xc7 } };
//ventoy_guid EspPartType = { 0xc12a7328, 0xf81f, 0x11d2, { 0xba, 0x4b, 0x00, 0xa0, 0xc9, 0x3e, 0xc9, 0x3b } };
//ventoy_guid BiosGrubPartType = { 0x21686148, 0x6449, 0x6e6f, { 0x74, 0x4e, 0x65, 0x65, 0x64, 0x45, 0x46, 0x49 } };
VentoyFillProtectMBR(size, &gpt->MBR);
if (reserve > 0)
{
ReservedSector += reserve / 512;
}
Part1SectorCount = DiskSectorCount - ReservedSector - (VTOYEFI_PART_BYTES / 512) - 2048;
ModSectorCount = (Part1SectorCount % 8);
if (ModSectorCount)
{
vlog("Part1SectorCount:%llu is not aligned by 4KB (%llu)\n", (_ull)Part1SectorCount, (_ull)ModSectorCount);
}
// check aligned with 4KB
if (align4k)
{
if (ModSectorCount)
{
vdebug("Disk need to align with 4KB %u\n", (uint32_t)ModSectorCount);
Part1SectorCount -= ModSectorCount;
}
else
{
vdebug("no need to align with 4KB\n");
}
}
memcpy(Head->Signature, "EFI PART", 8);
Head->Version[2] = 0x01;
Head->Length = 92;
Head->Crc = 0;
Head->EfiStartLBA = 1;
Head->EfiBackupLBA = DiskSectorCount - 1;
Head->PartAreaStartLBA = 34;
Head->PartAreaEndLBA = DiskSectorCount - 34;
ventoy_gen_preudo_uuid(&Head->DiskGuid);
Head->PartTblStartLBA = 2;
Head->PartTblTotNum = 128;
Head->PartTblEntryLen = 128;
memcpy(&(Table[0].PartType), &WindowsDataPartType, sizeof(ventoy_guid));
ventoy_gen_preudo_uuid(&(Table[0].PartGuid));
Table[0].StartLBA = 2048;
Table[0].LastLBA = 2048 + Part1SectorCount - 1;
Table[0].Attr = 0;
ventoy_fill_gpt_partname(Table[0].Name, "Ventoy");
// to fix windows issue
//memcpy(&(Table[1].PartType), &EspPartType, sizeof(GUID));
memcpy(&(Table[1].PartType), &WindowsDataPartType, sizeof(ventoy_guid));
ventoy_gen_preudo_uuid(&(Table[1].PartGuid));
Table[1].StartLBA = Table[0].LastLBA + 1;
Table[1].LastLBA = Table[1].StartLBA + VTOYEFI_PART_BYTES / 512 - 1;
Table[1].Attr = 0xC000000000000001ULL;
ventoy_fill_gpt_partname(Table[1].Name, "VTOYEFI");
#if 0
memcpy(&(Table[2].PartType), &BiosGrubPartType, sizeof(ventoy_guid));
ventoy_gen_preudo_uuid(&(Table[2].PartGuid));
Table[2].StartLBA = 34;
Table[2].LastLBA = 2047;
Table[2].Attr = 0;
#endif
//Update CRC
Head->PartTblCrc = ventoy_crc32(Table, sizeof(gpt->PartTbl));
Head->Crc = ventoy_crc32(Head, Head->Length);
return 0;
}
int VentoyFillMBRLocation(uint64_t DiskSizeInBytes, uint32_t StartSectorId, uint32_t SectorCount, PART_TABLE *Table)
{
uint8_t Head;
uint8_t Sector;
uint8_t nSector = 63;
uint8_t nHead = 8;
uint32_t Cylinder;
uint32_t EndSectorId;
while (nHead != 0 && (DiskSizeInBytes / 512 / nSector / nHead) > 1024)
{
nHead = (uint8_t)nHead * 2;
}
if (nHead == 0)
{
nHead = 255;
}
Cylinder = StartSectorId / nSector / nHead;
Head = StartSectorId / nSector % nHead;
Sector = StartSectorId % nSector + 1;
Table->StartHead = Head;
Table->StartSector = Sector;
Table->StartCylinder = Cylinder;
EndSectorId = StartSectorId + SectorCount - 1;
Cylinder = EndSectorId / nSector / nHead;
Head = EndSectorId / nSector % nHead;
Sector = EndSectorId % nSector + 1;
Table->EndHead = Head;
Table->EndSector = Sector;
Table->EndCylinder = Cylinder;
Table->StartSectorId = StartSectorId;
Table->SectorCount = SectorCount;
return 0;
}
int ventoy_fill_mbr(uint64_t size, uint64_t reserve, int align4k, MBR_HEAD *pMBR)
{
ventoy_guid Guid;
uint32_t DiskSignature;
uint32_t DiskSectorCount;
uint32_t PartSectorCount;
uint32_t PartStartSector;
uint32_t ReservedSector;
VentoyGetLocalBootImg(pMBR);
ventoy_gen_preudo_uuid(&Guid);
memcpy(&DiskSignature, &Guid, sizeof(uint32_t));
vdebug("Disk signature: 0x%08x\n", DiskSignature);
memcpy(pMBR->BootCode + 0x1B8, &DiskSignature, 4);
memcpy(pMBR->BootCode + 0x180, &Guid, 16);
if (size / 512 > 0xFFFFFFFF)
{
DiskSectorCount = 0xFFFFFFFF;
}
else
{
DiskSectorCount = (uint32_t)(size / 512);
}
if (reserve <= 0)
{
ReservedSector = 0;
}
else
{
ReservedSector = (uint32_t)(reserve / 512);
}
// check aligned with 4KB
if (align4k)
{
uint64_t sectors = size / 512;
if (sectors % 8)
{
vlog("Disk need to align with 4KB %u\n", (uint32_t)(sectors % 8));
ReservedSector += (uint32_t)(sectors % 8);
}
else
{
vdebug("no need to align with 4KB\n");
}
}
vlog("ReservedSector: %u\n", ReservedSector);
//Part1
PartStartSector = VTOYIMG_PART_START_SECTOR;
PartSectorCount = DiskSectorCount - ReservedSector - VTOYEFI_PART_BYTES / 512 - PartStartSector;
VentoyFillMBRLocation(size, PartStartSector, PartSectorCount, pMBR->PartTbl);
pMBR->PartTbl[0].Active = 0x80; // bootable
pMBR->PartTbl[0].FsFlag = 0x07; // exFAT/NTFS/HPFS
//Part2
PartStartSector += PartSectorCount;
PartSectorCount = VTOYEFI_PART_BYTES / 512;
VentoyFillMBRLocation(size, PartStartSector, PartSectorCount, pMBR->PartTbl + 1);
pMBR->PartTbl[1].Active = 0x00;
pMBR->PartTbl[1].FsFlag = 0xEF; // EFI System Partition
pMBR->Byte55 = 0x55;
pMBR->ByteAA = 0xAA;
return 0;
}
int ventoy_fill_mbr_4k(uint64_t size, uint64_t reserve, int align4k, MBR_HEAD *pMBR)
{
ventoy_guid Guid;
uint32_t DiskSignature;
uint32_t DiskSectorCount;
uint32_t PartSectorCount;
uint32_t PartStartSector;
uint32_t ReservedSector;
VentoyGetLocalBootImg(pMBR);
ventoy_gen_preudo_uuid(&Guid);
memcpy(&DiskSignature, &Guid, sizeof(uint32_t));
vdebug("Disk signature: 0x%08x\n", DiskSignature);
memcpy(pMBR->BootCode + 0x1B8, &DiskSignature, 4);
memcpy(pMBR->BootCode + 0x180, &Guid, 16);
if (size / 4096 > 0xFFFFFFFF)
{
DiskSectorCount = 0xFFFFFFFF;
}
else
{
DiskSectorCount = (uint32_t)(size / 4096);
}
if (reserve <= 0)
{
ReservedSector = 0;
}
else
{
ReservedSector = (uint32_t)(reserve / 4096);
}
// check aligned with 4KB
vdebug("no need to align with 4KB for 4K native disk\n");
vlog("ReservedSector: %u\n", ReservedSector);
//Part1
PartStartSector = VTOYIMG_PART_START_SECTOR >> 3;
PartSectorCount = DiskSectorCount - ReservedSector - VTOYEFI_PART_BYTES / 4096 - PartStartSector;
VentoyFillMBRLocation(size, PartStartSector, PartSectorCount, pMBR->PartTbl);
pMBR->PartTbl[0].Active = 0x80; // bootable
pMBR->PartTbl[0].FsFlag = 0x07; // exFAT/NTFS/HPFS
//Part2
PartStartSector += PartSectorCount;
PartSectorCount = VTOYEFI_PART_BYTES / 4096;
VentoyFillMBRLocation(size, PartStartSector, PartSectorCount, pMBR->PartTbl + 1);
pMBR->PartTbl[1].Active = 0x00;
pMBR->PartTbl[1].FsFlag = 0xEF; // EFI System Partition
pMBR->Byte55 = 0x55;
pMBR->ByteAA = 0xAA;
return 0;
}
| 15,410 |
C
|
.c
| 531 | 22.830508 | 132 | 0.58555 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
781 |
repair.c
|
ventoy_Ventoy/LinuxGUI/Ventoy2Disk/Lib/exfat/src/libexfat/repair.c
|
/*
repair.c (09.03.17)
exFAT file system implementation library.
Free exFAT implementation.
Copyright (C) 2010-2018 Andrew Nayenko
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "exfat.h"
#include <strings.h>
int exfat_errors_fixed;
bool exfat_ask_to_fix(const struct exfat* ef)
{
const char* question = "Fix (Y/N)?";
char answer[8];
bool yeah, nope;
switch (ef->repair)
{
case EXFAT_REPAIR_NO:
return false;
case EXFAT_REPAIR_YES:
printf("%s %s", question, "Y\n");
return true;
case EXFAT_REPAIR_ASK:
do
{
printf("%s ", question);
fflush(stdout);
if (fgets(answer, sizeof(answer), stdin))
{
yeah = strcasecmp(answer, "Y\n") == 0;
nope = strcasecmp(answer, "N\n") == 0;
}
else
{
yeah = false;
nope = true;
}
}
while (!yeah && !nope);
return yeah;
}
exfat_bug("invalid repair option value: %d", ef->repair);
return false;
}
bool exfat_fix_invalid_vbr_checksum(const struct exfat* ef, void* sector,
uint32_t vbr_checksum)
{
size_t i;
off_t sector_size = SECTOR_SIZE(*ef->sb);
for (i = 0; i < sector_size / sizeof(vbr_checksum); i++)
((le32_t*) sector)[i] = cpu_to_le32(vbr_checksum);
if (exfat_pwrite(ef->dev, sector, sector_size, 11 * sector_size) < 0)
{
exfat_error("failed to write correct VBR checksum");
return false;
}
exfat_errors_fixed++;
return true;
}
bool exfat_fix_invalid_node_checksum(const struct exfat* ef,
struct exfat_node* node)
{
/* checksum will be rewritten by exfat_flush_node() */
node->is_dirty = true;
exfat_errors_fixed++;
return true;
}
bool exfat_fix_unknown_entry(struct exfat* ef, struct exfat_node* dir,
const struct exfat_entry* entry, off_t offset)
{
struct exfat_entry deleted = *entry;
deleted.type &= ~EXFAT_ENTRY_VALID;
if (exfat_generic_pwrite(ef, dir, &deleted, sizeof(struct exfat_entry),
offset) != sizeof(struct exfat_entry))
return false;
exfat_errors_fixed++;
return true;
}
| 2,596 |
C
|
.c
| 88 | 26.977273 | 73 | 0.719214 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
831 |
dat.h
|
ventoy_Ventoy/VBLADE/vblade-master/dat.h
|
/* dat.h: include file for vblade AoE target */
#define nil ((void *)0)
/*
* tunable variables
*/
enum {
VBLADE_VERSION = 24,
// Firmware version
FWV = 0x4000 + VBLADE_VERSION,
};
#undef major
#undef minor
#undef makedev
#define major(x) ((x) >> 24 & 0xFF)
#define minor(x) ((x) & 0xffffff)
#define makedev(x, y) ((x) << 24 | (y))
typedef unsigned char uchar;
//typedef unsigned short ushort;
#ifdef __FreeBSD__
typedef unsigned long ulong;
#else
//typedef unsigned long ulong;
#endif
typedef long long vlong;
typedef struct Aoehdr Aoehdr;
typedef struct Ata Ata;
typedef struct Conf Conf;
typedef struct Ataregs Ataregs;
typedef struct Mdir Mdir;
typedef struct Aoemask Aoemask;
typedef struct Aoesrr Aoesrr;
struct Ataregs
{
vlong lba;
uchar cmd;
uchar status;
uchar err;
uchar feature;
uchar sectors;
};
struct Aoehdr
{
uchar dst[6];
uchar src[6];
ushort type;
uchar flags;
uchar error;
ushort maj;
uchar min;
uchar cmd;
uchar tag[4];
};
struct Ata
{
Aoehdr h;
uchar aflag;
uchar err;
uchar sectors;
uchar cmd;
uchar lba[6];
uchar resvd[2];
};
struct Conf
{
Aoehdr h;
ushort bufcnt;
ushort firmware;
uchar scnt;
uchar vercmd;
ushort len;
uchar data[1024];
};
// mask directive
struct Mdir {
uchar res;
uchar cmd;
uchar mac[6];
};
struct Aoemask {
Aoehdr h;
uchar res;
uchar cmd;
uchar merror;
uchar nmacs;
// struct Mdir m[0];
};
struct Aoesrr {
Aoehdr h;
uchar rcmd;
uchar nmacs;
// uchar mac[6][nmacs];
};
enum {
AoEver = 1,
ATAcmd = 0, // command codes
Config,
Mask,
Resrel,
Resp = (1<<3), // flags
Error = (1<<2),
BadCmd = 1,
BadArg,
DevUnavailable,
ConfigErr,
BadVersion,
Res,
Write = (1<<0),
Async = (1<<1),
Device = (1<<4),
Extend = (1<<6),
Qread = 0,
Qtest,
Qprefix,
Qset,
Qfset,
Nretries = 3,
Nconfig = 1024,
Bufcount = 16,
/* mask commands */
Mread= 0,
Medit,
/* mask directives */
MDnop= 0,
MDadd,
MDdel,
/* mask errors */
MEunspec= 1,
MEbaddir,
MEfull,
/* header sizes, including aoe hdr */
Naoehdr= 24,
Natahdr= Naoehdr + 12,
Ncfghdr= Naoehdr + 8,
Nmaskhdr= Naoehdr + 4,
Nsrrhdr= Naoehdr + 2,
Nserial= 20,
};
int shelf, slot;
ulong aoetag;
uchar mac[6];
int bfd; // block file descriptor
int sfd; // socket file descriptor
vlong size; // size of vblade
vlong offset;
char *progname;
char serial[Nserial+1];
| 2,349 |
C
|
.h
| 146 | 14.294521 | 47 | 0.710345 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
832 |
linux.h
|
ventoy_Ventoy/VBLADE/vblade-master/linux.h
|
// linux.h: header for linux.c
typedef unsigned char uchar;
typedef long long vlong;
int dial(char *);
int getindx(int, char *);
int getea(int, char *, uchar *);
int getsec(int, uchar *, vlong, int);
int putsec(int, uchar *, vlong, int);
vlong getsize(int);
| 260 |
C
|
.h
| 9 | 27.666667 | 37 | 0.714859 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
833 |
fns.h
|
ventoy_Ventoy/VBLADE/vblade-master/fns.h
|
// fns.h: function prototypes
// aoe.c
void aoe(void);
void aoeinit(void);
void aoequery(void);
void aoeconfig(void);
void aoead(int);
void aoeflush(int, int);
void aoetick(void);
void aoerequest(int, int, vlong, int, uchar *, int);
int maskok(uchar *);
int rrok(uchar *);
// ata.c
void atainit(void);
int atacmd(Ataregs *, uchar *, int, int);
// bpf.c
void * create_bpf_program(int, int);
void free_bpf_program(void *);
// os specific
int dial(char *, int);
int getea(int, char *, uchar *);
int putsec(int, uchar *, vlong, int);
int getsec(int, uchar *, vlong, int);
int putpkt(int, uchar *, int);
int getpkt(int, uchar *, int);
vlong getsize(int);
int getmtu(int, char *);
| 683 |
C
|
.h
| 27 | 24 | 52 | 0.70216 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
918 |
info.h
|
ventoy_Ventoy/SQUASHFS/squashfs-tools-4.4/squashfs-tools/info.h
|
#ifndef INFO_H
#define INFO_H
/*
* Create a squashfs filesystem. This is a highly compressed read only
* filesystem.
*
* Copyright (c) 2013, 2014
* Phillip Lougher <[email protected]>
*
* 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,
* 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, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* info.h
*/
extern void disable_info();
extern void update_info(struct dir_ent *);
extern void init_info();
#endif
| 1,013 |
C
|
.h
| 29 | 33.137931 | 71 | 0.756867 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
920 |
read_fs.h
|
ventoy_Ventoy/SQUASHFS/squashfs-tools-4.4/squashfs-tools/read_fs.h
|
#ifndef READ_FS_H
#define READ_FS_H
/*
* Squashfs
*
* Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2013
* Phillip Lougher <[email protected]>
*
* 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,
* 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, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* read_fs.h
*
*/
extern struct compressor *read_super(int, struct squashfs_super_block *,
char *);
extern long long read_filesystem(char *, int, struct squashfs_super_block *,
char **, char **, char **, char **, unsigned int *, unsigned int *,
unsigned int *, unsigned int *, unsigned int *, int *, int *, int *, int *,
int *, int *, long long *, unsigned int *, unsigned int *, unsigned int *,
unsigned int *, void (push_directory_entry)(char *, squashfs_inode, int, int),
struct squashfs_fragment_entry **, squashfs_inode **);
#endif
| 1,414 |
C
|
.h
| 34 | 39.911765 | 78 | 0.724638 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
921 |
lzo_wrapper.h
|
ventoy_Ventoy/SQUASHFS/squashfs-tools-4.4/squashfs-tools/lzo_wrapper.h
|
#ifndef LZO_WRAPPER_H
#define LZO_WRAPPER_H
/*
* Squashfs
*
* Copyright (c) 2013
* Phillip Lougher <[email protected]>
*
* 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,
* 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, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* lzo_wrapper.h
*
*/
#ifndef linux
#define __BYTE_ORDER BYTE_ORDER
#define __BIG_ENDIAN BIG_ENDIAN
#define __LITTLE_ENDIAN LITTLE_ENDIAN
#else
#include <endian.h>
#endif
#if __BYTE_ORDER == __BIG_ENDIAN
extern unsigned int inswap_le32(unsigned int);
#define SQUASHFS_INSWAP_COMP_OPTS(s) { \
(s)->algorithm = inswap_le32((s)->algorithm); \
(s)->compression_level = inswap_le32((s)->compression_level); \
}
#else
#define SQUASHFS_INSWAP_COMP_OPTS(s)
#endif
/* Define the compression flags recognised. */
#define SQUASHFS_LZO1X_1 0
#define SQUASHFS_LZO1X_1_11 1
#define SQUASHFS_LZO1X_1_12 2
#define SQUASHFS_LZO1X_1_15 3
#define SQUASHFS_LZO1X_999 4
/* Default compression level used by SQUASHFS_LZO1X_999 */
#define SQUASHFS_LZO1X_999_COMP_DEFAULT 8
struct lzo_comp_opts {
int algorithm;
int compression_level;
};
struct lzo_algorithm {
char *name;
int size;
int (*compress) (const lzo_bytep, lzo_uint, lzo_bytep, lzo_uintp,
lzo_voidp);
};
struct lzo_stream {
void *workspace;
void *buffer;
};
#define LZO_MAX_EXPANSION(size) (size + (size / 16) + 64 + 3)
int lzo1x_999_wrapper(const lzo_bytep, lzo_uint, lzo_bytep, lzo_uintp,
lzo_voidp);
#endif
| 2,000 |
C
|
.h
| 67 | 28.164179 | 71 | 0.74974 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
926 |
unsquashfs_info.h
|
ventoy_Ventoy/SQUASHFS/squashfs-tools-4.4/squashfs-tools/unsquashfs_info.h
|
#ifndef UNSQUASHFS_INFO_H
#define UNSQUASHFS_INFO_H
/*
* Create a squashfs filesystem. This is a highly compressed read only
* filesystem.
*
* Copyright (c) 2013, 2014
* Phillip Lougher <[email protected]>
*
* 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,
* 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, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* unsquashfs_info.h
*/
extern void disable_info();
extern void update_info(char *);
extern void init_info();
#endif
| 1,036 |
C
|
.h
| 29 | 33.931034 | 71 | 0.761431 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
927 |
pseudo.h
|
ventoy_Ventoy/SQUASHFS/squashfs-tools-4.4/squashfs-tools/pseudo.h
|
#ifndef PSEUDO_H
#define PSEUDO_H
/*
* Create a squashfs filesystem. This is a highly compressed read only
* filesystem.
*
* Copyright (c) 2009, 2010, 2014
* Phillip Lougher <[email protected]>
*
* 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,
* 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, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* pseudo.h
*/
struct pseudo_dev {
char type;
unsigned int mode;
unsigned int uid;
unsigned int gid;
unsigned int major;
unsigned int minor;
int pseudo_id;
union {
char *command;
char *symlink;
};
};
struct pseudo_entry {
char *name;
char *pathname;
struct pseudo *pseudo;
struct pseudo_dev *dev;
};
struct pseudo {
int names;
int count;
struct pseudo_entry *name;
};
extern int read_pseudo_def(char *);
extern int read_pseudo_file(char *);
extern struct pseudo *pseudo_subdir(char *, struct pseudo *);
extern struct pseudo_entry *pseudo_readdir(struct pseudo *);
extern struct pseudo_dev *get_pseudo_file(int);
extern int pseudo_exec_file(struct pseudo_dev *, int *);
extern struct pseudo *get_pseudo();
extern void dump_pseudos();
#endif
| 1,683 |
C
|
.h
| 58 | 27.224138 | 71 | 0.74892 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
940 |
restore.h
|
ventoy_Ventoy/SQUASHFS/squashfs-tools-4.4/squashfs-tools/restore.h
|
#ifndef RESTORE_H
#define RESTORE_H
/*
* Create a squashfs filesystem. This is a highly compressed read only
* filesystem.
*
* Copyright (c) 2013, 2014
* Phillip Lougher <[email protected]>
*
* 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,
* 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, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* restore.h
*/
extern pthread_t *init_restore_thread();
#endif
| 967 |
C
|
.h
| 27 | 33.962963 | 71 | 0.759318 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
941 |
lz4_wrapper.h
|
ventoy_Ventoy/SQUASHFS/squashfs-tools-4.4/squashfs-tools/lz4_wrapper.h
|
#ifndef LZ4_WRAPPER_H
#define LZ4_WRAPPER_H
/*
* Squashfs
*
* Copyright (c) 2013
* Phillip Lougher <[email protected]>
*
* 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,
* 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, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* lz4_wrapper.h
*
*/
#ifndef linux
#define __BYTE_ORDER BYTE_ORDER
#define __BIG_ENDIAN BIG_ENDIAN
#define __LITTLE_ENDIAN LITTLE_ENDIAN
#else
#include <endian.h>
#endif
#if __BYTE_ORDER == __BIG_ENDIAN
extern unsigned int inswap_le32(unsigned int);
#define SQUASHFS_INSWAP_COMP_OPTS(s) { \
(s)->version = inswap_le32((s)->version); \
(s)->flags = inswap_le32((s)->flags); \
}
#else
#define SQUASHFS_INSWAP_COMP_OPTS(s)
#endif
/*
* Define the various stream formats recognised.
* Currently omly legacy stream format is supported by the
* kernel
*/
#define LZ4_LEGACY 1
#define LZ4_FLAGS_MASK 1
/* Define the compression flags recognised. */
#define LZ4_HC 1
struct lz4_comp_opts {
int version;
int flags;
};
#endif
| 1,561 |
C
|
.h
| 55 | 26.727273 | 71 | 0.748667 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
942 |
sort.h
|
ventoy_Ventoy/SQUASHFS/squashfs-tools-4.4/squashfs-tools/sort.h
|
#ifndef SORT_H
#define SORT_H
/*
* Squashfs
*
* Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2013
* Phillip Lougher <[email protected]>
*
* 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,
* 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, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* sort.h
*/
struct priority_entry {
struct dir_ent *dir;
struct priority_entry *next;
};
extern int read_sort_file(char *, int, char *[]);
extern void sort_files_and_write(struct dir_info *);
extern void generate_file_priorities(struct dir_info *, int priority,
struct stat *);
extern struct priority_entry *priority_list[65536];
#endif
| 1,215 |
C
|
.h
| 34 | 33.911765 | 75 | 0.750424 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
970 |
strings.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/strings.h
|
#ifndef _STRINGS_H
#define _STRINGS_H
/*
* Copyright (C) 2012 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* String operations
*
*/
extern int strcasecmp ( const char *str1, const char *str2 );
#endif /* _STRINGS_H */
| 966 |
C
|
.h
| 28 | 32.571429 | 70 | 0.744111 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
972 |
compiler.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/compiler.h
|
#ifndef _COMPILER_H
#define _COMPILER_H
/*
* Copyright (C) 2012 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* Global compiler definitions
*
*/
/* Force visibility of all symbols to "hidden", i.e. inform gcc that
* all symbol references resolve strictly within our final binary.
* This avoids unnecessary PLT/GOT entries on x86_64.
*
* This is a stronger claim than specifying "-fvisibility=hidden",
* since it also affects symbols marked with "extern".
*/
#ifndef ASSEMBLY
#if __GNUC__ >= 4
#pragma GCC visibility push(hidden)
#endif
#endif /* ASSEMBLY */
#endif /* _COMPILER_H */
| 1,336 |
C
|
.h
| 39 | 32.435897 | 70 | 0.747873 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
973 |
memmap.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/memmap.h
|
#ifndef _MEMMAP_H
#define _MEMMAP_H
/*
* Copyright (C) 2021 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* Memory map
*
*/
#include <stdint.h>
/** Magic value for INT 15,e820 calls */
#define E820_SMAP 0x534d4150
/** An INT 15,e820 memory map entry */
struct e820_entry {
/** Start of region */
uint64_t start;
/** Length of region */
uint64_t len;
/** Type of region */
uint32_t type;
/** Extended attributes (optional) */
uint32_t attrs;
} __attribute__ (( packed ));
/** Normal RAM */
#define E820_TYPE_RAM 1
/** Region is enabled (if extended attributes are present) */
#define E820_ATTR_ENABLED 0x00000001UL
/** Region is non-volatile memory (if extended attributes are present) */
#define E820_ATTR_NONVOLATILE 0x00000002UL
extern struct e820_entry * memmap_next ( struct e820_entry *prev );
#endif /* _MEMMAP_H */
| 1,583 |
C
|
.h
| 48 | 31.145833 | 73 | 0.732459 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
974 |
wimboot.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/wimboot.h
|
#ifndef _WIMBOOT_H
#define _WIMBOOT_H
/*
* Copyright (C) 2012 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* WIM boot loader
*
*/
/** Debug switch */
#ifndef DEBUG
#define DEBUG 1
#endif
/** Base segment address
*
* We place everything at 2000:0000, since this region is used by the
* Microsoft first-stage loaders (e.g. pxeboot.n12, etfsboot.com).
*/
#define BASE_SEG 0x2000
/** Base linear address */
#define BASE_ADDRESS ( BASE_SEG << 4 )
/** 64 bit long mode code segment */
#define LM_CS 0x10
/** 32 bit protected mode flat code segment */
#define FLAT_CS 0x20
/** 32 bit protected mode flat data segment */
#define FLAT_DS 0x30
/** 16 bit real mode code segment */
#define REAL_CS 0x50
/** 16 bit real mode data segment */
#define REAL_DS 0x60
#ifndef ASSEMBLY
#include <stdint.h>
#include <bootapp.h>
#include <cmdline.h>
/** Construct wide-character version of a string constant */
#define L( x ) _L ( x )
#define _L( x ) L ## x
/** Page size */
#define PAGE_SIZE 4096
/**
* Calculate start page number
*
* @v address Address
* @ret page Start page number
*/
static inline unsigned int page_start ( const void *address ) {
return ( ( ( intptr_t ) address ) / PAGE_SIZE );
}
/**
* Calculate end page number
*
* @v address Address
* @ret page End page number
*/
static inline unsigned int page_end ( const void *address ) {
return ( ( ( ( intptr_t ) address ) + PAGE_SIZE - 1 ) / PAGE_SIZE );
}
/**
* Calculate page length
*
* @v start Start address
* @v end End address
* @ret num_pages Number of pages
*/
static inline unsigned int page_len ( const void *start, const void *end ) {
return ( page_end ( end ) - page_start ( start ) );
}
/**
* Bochs magic breakpoint
*
*/
static inline void bochsbp ( void ) {
__asm__ __volatile__ ( "xchgw %bx, %bx" );
}
/** Debugging output */
#define DBG(...) do { \
if ( ( DEBUG & 1 ) && ( ! cmdline_quiet ) ) { \
printf ( __VA_ARGS__ ); \
} \
} while ( 0 )
/** Verbose debugging output */
#define DBG2(...) do { \
if ( ( DEBUG & 2 ) && ( ! cmdline_quiet ) ) { \
printf ( __VA_ARGS__ ); \
} \
} while ( 0 )
/* Branch prediction macros */
#define likely( x ) __builtin_expect ( !! (x), 1 )
#define unlikely( x ) __builtin_expect ( (x), 0 )
/* Mark parameter as unused */
#define __unused __attribute__ (( unused ))
#if __x86_64__
static inline void call_real ( struct bootapp_callback_params *params ) {
/* Not available in 64-bit mode */
( void ) params;
}
static inline void call_interrupt ( struct bootapp_callback_params *params ) {
/* Not available in 64-bit mode */
( void ) params;
}
static inline void reboot ( void ) {
/* Not available in 64-bit mode */
}
#else
extern void call_real ( struct bootapp_callback_params *params );
extern void call_interrupt ( struct bootapp_callback_params *params );
extern void __attribute__ (( noreturn )) reboot ( void );
#endif
extern void __attribute__ (( noreturn, format ( printf, 1, 2 ) ))
die ( const char *fmt, ... );
extern unsigned long __stack_chk_guard;
extern void init_cookie ( void );
#endif /* ASSEMBLY */
#endif /* _WIMBOOT_H */
| 3,880 |
C
|
.h
| 132 | 27.659091 | 78 | 0.677237 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
975 |
peloader.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/peloader.h
|
#ifndef _PELOADER_H
#define _PELOADER_H
/*
* Copyright (C) 2012 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* PE image loader
*
*/
#include <stdint.h>
#include "wimboot.h"
/** DOS MZ header */
struct mz_header {
/** Magic number */
uint16_t magic;
/** Bytes on last page of file */
uint16_t cblp;
/** Pages in file */
uint16_t cp;
/** Relocations */
uint16_t crlc;
/** Size of header in paragraphs */
uint16_t cparhdr;
/** Minimum extra paragraphs needed */
uint16_t minalloc;
/** Maximum extra paragraphs needed */
uint16_t maxalloc;
/** Initial (relative) SS value */
uint16_t ss;
/** Initial SP value */
uint16_t sp;
/** Checksum */
uint16_t csum;
/** Initial IP value */
uint16_t ip;
/** Initial (relative) CS value */
uint16_t cs;
/** File address of relocation table */
uint16_t lfarlc;
/** Overlay number */
uint16_t ovno;
/** Reserved words */
uint16_t res[4];
/** OEM identifier (for oeminfo) */
uint16_t oemid;
/** OEM information; oemid specific */
uint16_t oeminfo;
/** Reserved words */
uint16_t res2[10];
/** File address of new exe header */
uint32_t lfanew;
} __attribute__ (( packed ));
/** MZ header magic */
#define MZ_HEADER_MAGIC 0x5a4d
/** COFF file header */
struct coff_header {
/** Magic number */
uint16_t magic;
/** Number of sections */
uint16_t num_sections;
/** Timestamp (seconds since the Epoch) */
uint32_t timestamp;
/** Offset to symbol table */
uint32_t symtab;
/** Number of symbol table entries */
uint32_t num_syms;
/** Length of optional header */
uint16_t opthdr_len;
/** Flags */
uint16_t flags;
} __attribute__ (( packed ));
/** COFF section */
struct coff_section {
/** Section name */
char name[8];
/** Physical address or virtual length */
union {
/** Physical address */
uint32_t physical;
/** Virtual length */
uint32_t virtual_len;
} misc;
/** Virtual address */
uint32_t virtual;
/** Length of raw data */
uint32_t raw_len;
/** Offset to raw data */
uint32_t raw;
/** Offset to relocations */
uint32_t relocations;
/** Offset to line numbers */
uint32_t line_numbers;
/** Number of relocations */
uint16_t num_relocations;
/** Number of line numbers */
uint16_t num_line_numbers;
/** Flags */
uint32_t flags;
} __attribute__ (( packed ));
/** PE file header */
struct pe_header {
/** Magic number */
uint32_t magic;
/** COFF header */
struct coff_header coff;
} __attribute__ (( packed ));
/** PE header magic */
#define PE_HEADER_MAGIC 0x00004550
/** PE optional header */
struct pe_optional_header {
/** Magic number */
uint16_t magic;
/** Major linker version */
uint8_t linker_major;
/** Minor linker version */
uint8_t linker_minor;
/** Length of code */
uint32_t text_len;
/** Length of initialised data */
uint32_t data_len;
/** Length of uninitialised data */
uint32_t bss_len;
/** Entry point */
uint32_t entry;
/** Base of code */
uint32_t text;
/** Base of data */
uint32_t data;
/** Image base address */
uint32_t base;
/** Section alignment */
uint32_t section_align;
/** File alignment */
uint32_t file_align;
/** Major operating system version */
uint16_t os_major;
/** Minor operating system version */
uint16_t os_minor;
/** Major image version */
uint16_t image_major;
/** Minor image version */
uint16_t image_minor;
/** Major subsystem version */
uint16_t subsystem_major;
/** Minor subsystem version */
uint16_t subsystem_minor;
/** Win32 version */
uint32_t win32_version;
/** Size of image */
uint32_t len;
/** Size of headers */
uint32_t header_len;
/* Plus extra fields that we don't care about */
} __attribute__ (( packed ));
/** A loaded PE image */
struct loaded_pe {
/** Base address */
void *base;
/** Length */
size_t len;
/** Entry point */
void ( * entry ) ( struct bootapp_descriptor *bootapp );
};
extern int load_pe ( const void *data, size_t len, struct loaded_pe *pe );
#endif /* _PELOADER_H */
| 4,676 |
C
|
.h
| 182 | 23.763736 | 74 | 0.685338 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
976 |
stdio.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/stdio.h
|
#ifndef _STDIO_H
#define _STDIO_H
/*
* Copyright (C) 2012 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* Standard Input/Output
*
*/
#include <stdint.h>
#include <stdarg.h>
extern int putchar ( int character );
extern int getchar ( void );
extern int __attribute__ (( format ( printf, 1, 2 ) ))
printf ( const char *fmt, ... );
extern int __attribute__ (( format ( printf, 3, 4 ) ))
snprintf ( char *buf, size_t size, const char *fmt, ... );
extern int vprintf ( const char *fmt, va_list args );
extern int vsnprintf ( char *buf, size_t size, const char *fmt, va_list args );
#endif /* _STDIO_H */
| 1,350 |
C
|
.h
| 37 | 34.648649 | 79 | 0.717025 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
978 |
vdisk.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/vdisk.h
|
#ifndef _VDISK_H
#define _VDISK_H
/*
* Copyright (C) 2012 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* Virtual disk emulation
*
*/
#include <stdint.h>
/** Number of cylinders */
#define VDISK_CYLINDERS 1024 /* Maximum possible */
/** Number of heads */
#define VDISK_HEADS 255
/** Number of sectors per track */
#define VDISK_SECTORS_PER_TRACK 63
/** Sector size (in bytes) */
#define VDISK_SECTOR_SIZE 512
/** Partition start LBA */
#define VDISK_PARTITION_LBA 128
/** Cluster size (in sectors) */
#define VDISK_CLUSTER_COUNT 64
/** Cluster size (in bytes) */
#define VDISK_CLUSTER_SIZE ( VDISK_CLUSTER_COUNT * VDISK_SECTOR_SIZE )
/** Number of clusters */
#define VDISK_CLUSTERS 0x03ffc000ULL /* Fill 2TB disk */
/** Maximum number of virtual files
*
* The total number of files must be strictly less than the number of
* sectors per cluster.
*/
#define VDISK_MAX_FILES ( VDISK_CLUSTER_COUNT - 1 )
/** Maximum file size (in sectors) */
#define VDISK_FILE_COUNT 0x800000UL /* max for 32-bit address space */
/** Maximum file size (in clusters) */
#define VDISK_FILE_CLUSTERS ( VDISK_FILE_COUNT / VDISK_CLUSTER_COUNT )
/** File starting LBA */
#define VDISK_FILE_LBA( idx ) ( ( (idx) + 1 ) * VDISK_FILE_COUNT )
/** File index from LBA */
#define VDISK_FILE_IDX( lba ) ( ( (lba) / VDISK_FILE_COUNT ) - 1 )
/** File offset (in bytes) from LBA */
#define VDISK_FILE_OFFSET( lba ) \
( ( (lba) % VDISK_FILE_COUNT ) * VDISK_SECTOR_SIZE )
/** File index from directory entry LBA */
#define VDISK_FILE_DIRENT_IDX( lba ) ( ( (lba) - 1 ) % VDISK_CLUSTER_COUNT )
/** Number of sectors allocated for FAT */
#define VDISK_SECTORS_PER_FAT \
( ( ( VDISK_CLUSTERS * sizeof ( uint32_t ) + \
VDISK_CLUSTER_SIZE - 1 ) / VDISK_CLUSTER_SIZE ) \
* VDISK_CLUSTER_COUNT )
/** Number of reserved sectors */
#define VDISK_RESERVED_COUNT VDISK_CLUSTER_COUNT
/** Starting cluster number for file */
#define VDISK_FILE_CLUSTER( idx ) \
( ( ( ( VDISK_FILE_COUNT - VDISK_PARTITION_LBA - \
VDISK_RESERVED_COUNT - VDISK_SECTORS_PER_FAT ) / \
VDISK_CLUSTER_COUNT ) + 2 ) + \
( (idx) * VDISK_FILE_CLUSTERS ) )
/** Total number of sectors within partition */
#define VDISK_PARTITION_COUNT \
( VDISK_RESERVED_COUNT + VDISK_SECTORS_PER_FAT + \
( VDISK_CLUSTERS * VDISK_CLUSTER_COUNT ) )
/** Number of sectors */
#define VDISK_COUNT ( VDISK_PARTITION_LBA + VDISK_PARTITION_COUNT )
/** Calculate sector from cluster */
#define VDISK_CLUSTER_SECTOR( cluster ) \
( ( ( (cluster) - 2 ) * VDISK_CLUSTER_COUNT ) + \
VDISK_RESERVED_COUNT + VDISK_SECTORS_PER_FAT )
/*****************************************************************************
*
* Master Boot Record
*
*****************************************************************************
*/
/** Master Boot Record LBA */
#define VDISK_MBR_LBA 0x00000000
/** Master Boot Record sector count */
#define VDISK_MBR_COUNT 1
/** Partition table entry */
struct vdisk_partition {
/** Bootable flag */
uint8_t bootable;
/** C/H/S start address */
uint8_t chs_start[3];
/** System indicator (partition type) */
uint8_t type;
/** C/H/S end address */
uint8_t chs_end[3];
/** Linear start address */
uint32_t start;
/** Linear length */
uint32_t length;
} __attribute__ (( packed ));
/** Master Boot Record */
struct vdisk_mbr {
/** Code area */
uint8_t code[440];
/** Disk signature */
uint32_t signature;
/** Padding */
uint8_t pad[2];
/** Partition table */
struct vdisk_partition partitions[4];
/** 0x55aa signature */
uint16_t magic;
} __attribute__ (( packed ));
/** MBR boot partition indiciator */
#define VDISK_MBR_BOOTABLE 0x80
/** MBR type indicator for FAT32 */
#define VDISK_MBR_TYPE_FAT32 0x0c
/** MBR signature */
#define VDISK_MBR_SIGNATURE 0xc0ffeeee
/** MBR magic */
#define VDISK_MBR_MAGIC 0xaa55
/*****************************************************************************
*
* Volume Boot Record
*
*****************************************************************************
*/
/** Volume Boot Record LBA */
#define VDISK_VBR_LBA VDISK_PARTITION_LBA
/** Volume Boot Record sector count */
#define VDISK_VBR_COUNT 1
/** Volume Boot Record */
struct vdisk_vbr {
/** Jump instruction */
uint8_t jump[3];
/** OEM identifier */
char oemid[8];
/** Number of bytes per sector */
uint16_t bytes_per_sector;
/** Number of sectors per cluster */
uint8_t sectors_per_cluster;
/** Number of reserved sectors */
uint16_t reserved_sectors;
/** Number of FATs */
uint8_t fats;
/** Number of root directory entries (FAT12/FAT16 only) */
uint16_t root_directory_entries;
/** Total number of sectors (0 if more than 65535) */
uint16_t sectors_short;
/** Media descriptor type */
uint8_t media;
/** Number of sectors per FAT (FAT12/FAT16 only) */
uint16_t sectors_per_fat_short;
/** Number of sectors per track */
uint16_t sectors_per_track;
/** Number of heads */
uint16_t heads;
/** Number of hidden sectors (i.e. LBA of start of partition) */
uint32_t hidden_sectors;
/** Total number of sectors */
uint32_t sectors;
/* FAT32-specific fields */
/** Sectors per FAT */
uint32_t sectors_per_fat;
/** Flags */
uint16_t flags;
/** FAT version number */
uint16_t version;
/** Root directory cluster */
uint32_t root;
/** FSInfo sector */
uint16_t fsinfo;
/** Backup boot sector */
uint16_t backup;
/** Reserved */
uint8_t reserved[12];
/** Drive number */
uint8_t drive;
/** Windows NT flags */
uint8_t nt_flags;
/** Signature */
uint8_t signature;
/** Volume ID serial */
uint32_t serial;
/** Label (space-padded) */
char label[11];
/** System identifier */
char system[8];
/** Boot code */
uint8_t code[420];
/** 0x55aa signature */
uint16_t magic;
} __attribute__ (( packed ));
/** VBR jump instruction
*
* bootmgr.exe will actually fail unless this is present. Someone
* must read specification documents without bothering to understand
* what's really happening.
*/
#define VDISK_VBR_JUMP_WTF_MS 0xe9
/** VBR OEM ID */
#define VDISK_VBR_OEMID "wimboot\0"
/** VBR media type */
#define VDISK_VBR_MEDIA 0xf8
/** VBR signature */
#define VDISK_VBR_SIGNATURE 0x29
/** VBR serial number */
#define VDISK_VBR_SERIAL 0xf00df00d
/** VBR label */
#define VDISK_VBR_LABEL "wimboot "
/** VBR system identifier */
#define VDISK_VBR_SYSTEM "FAT32 "
/** VBR magic */
#define VDISK_VBR_MAGIC 0xaa55
/*****************************************************************************
*
* FSInfo
*
*****************************************************************************
*/
/** FSInfo sector */
#define VDISK_FSINFO_SECTOR 0x00000001
/** FSInfo LBA */
#define VDISK_FSINFO_LBA ( VDISK_VBR_LBA + VDISK_FSINFO_SECTOR )
/** FSInfo sector count */
#define VDISK_FSINFO_COUNT 1
/** FSInfo */
struct vdisk_fsinfo {
/** First signature */
uint32_t magic1;
/** Reserved */
uint8_t reserved_1[480];
/** Second signature */
uint32_t magic2;
/** Free cluster count */
uint32_t free_count;
/** Next free cluster */
uint32_t next_free;
/** Reserved */
uint8_t reserved_2[12];
/** Third signature */
uint32_t magic3;
} __attribute__ (( packed ));
/** FSInfo first signature */
#define VDISK_FSINFO_MAGIC1 0x41615252
/** FSInfo second signature */
#define VDISK_FSINFO_MAGIC2 0x61417272
/** FSInfo next free cluster */
#define VDISK_FSINFO_NEXT_FREE 0xffffffff /* No free clusters */
/** FSInfo third signature */
#define VDISK_FSINFO_MAGIC3 0xaa550000
/*****************************************************************************
*
* Backup Volume Boot Record
*
*****************************************************************************
*/
/** Backup Volume Boot Record sector */
#define VDISK_BACKUP_VBR_SECTOR 0x00000006
/** Backup Volume Boot Record LBA */
#define VDISK_BACKUP_VBR_LBA ( VDISK_VBR_LBA + VDISK_BACKUP_VBR_SECTOR )
/** Backup Volume Boot Record sector count */
#define VDISK_BACKUP_VBR_COUNT 1
/*****************************************************************************
*
* File Allocation Table
*
*****************************************************************************
*/
/** FAT sector */
#define VDISK_FAT_SECTOR VDISK_RESERVED_COUNT
/** FAT LBA */
#define VDISK_FAT_LBA ( VDISK_VBR_LBA + VDISK_FAT_SECTOR )
/** FAT sector count */
#define VDISK_FAT_COUNT VDISK_SECTORS_PER_FAT
/** FAT end marker */
#define VDISK_FAT_END_MARKER 0x0ffffff8
/*****************************************************************************
*
* Directory entries
*
*****************************************************************************
*/
/** An 8.3 filename record */
struct vdisk_short_filename {
/** Filename */
union {
/** Structured 8.3 base name and extension */
struct {
/** Base name */
char base[8];
/** Extension */
char ext[3];
} __attribute__ (( packed ));
/** Raw bytes */
uint8_t raw[11];
} filename;
/** Attributes */
uint8_t attr;
/** Reserved */
uint8_t reserved;
/** Creation time in tenths of a second */
uint8_t created_deciseconds;
/** Creation time (HMS packed) */
uint16_t created_time;
/** Creation date (YMD packed) */
uint16_t created_date;
/** Last accessed date (YMD packed) */
uint16_t accessed_date;
/** High 16 bits of starting cluster number */
uint16_t cluster_high;
/** Modification time (HMS packed) */
uint16_t modified_time;
/** Modification date (YMD packed) */
uint16_t modified_date;
/** Low 16 bits of starting cluster number */
uint16_t cluster_low;
/** Size */
uint32_t size;
} __attribute__ (( packed ));
/** A long filename record */
struct vdisk_long_filename {
/** Sequence number */
uint8_t sequence;
/** Name characters */
uint16_t name_1[5];
/** Attributes */
uint8_t attr;
/** Type */
uint8_t type;
/** Checksum of 8.3 name */
uint8_t checksum;
/** Name characters */
uint16_t name_2[6];
/** Reserved */
uint16_t reserved;
/** Name characters */
uint16_t name_3[2];
} __attribute__ (( packed ));
/** Directory entry attributes */
enum vdisk_directory_entry_attributes {
VDISK_READ_ONLY = 0x01,
VDISK_HIDDEN = 0x02,
VDISK_SYSTEM = 0x04,
VDISK_VOLUME_LABEL = 0x08,
VDISK_DIRECTORY = 0x10,
};
/** Long filename end-of-sequence marker */
#define VDISK_LFN_END 0x40
/** Long filename attributes */
#define VDISK_LFN_ATTR \
( VDISK_READ_ONLY | VDISK_HIDDEN | VDISK_SYSTEM | VDISK_VOLUME_LABEL )
/** A directory entry */
union vdisk_directory_entry {
/** Deleted file marker */
uint8_t deleted;
/** 8.3 filename */
struct vdisk_short_filename dos;
/** Long filename */
struct vdisk_long_filename lfn;
} __attribute__ (( packed ));
/** Magic marker for deleted files */
#define VDISK_DIRENT_DELETED 0xe5
/** Number of directory entries per sector */
#define VDISK_DIRENT_PER_SECTOR \
( VDISK_SECTOR_SIZE / \
sizeof ( union vdisk_directory_entry ) )
/** A directory sector */
struct vdisk_directory {
/** Entries */
union vdisk_directory_entry entry[VDISK_DIRENT_PER_SECTOR];
} __attribute__ (( packed ));
/*****************************************************************************
*
* Root directory
*
*****************************************************************************
*/
/** Root directory cluster */
#define VDISK_ROOT_CLUSTER 2
/** Root directory sector */
#define VDISK_ROOT_SECTOR VDISK_CLUSTER_SECTOR ( VDISK_ROOT_CLUSTER )
/** Root directory LBA */
#define VDISK_ROOT_LBA ( VDISK_VBR_LBA + VDISK_ROOT_SECTOR )
/*****************************************************************************
*
* Boot directory
*
*****************************************************************************
*/
/** Boot directory cluster */
#define VDISK_BOOT_CLUSTER 3
/** Boot directory sector */
#define VDISK_BOOT_SECTOR VDISK_CLUSTER_SECTOR ( VDISK_BOOT_CLUSTER )
/** Boot directory LBA */
#define VDISK_BOOT_LBA ( VDISK_VBR_LBA + VDISK_BOOT_SECTOR )
/*****************************************************************************
*
* Sources directory
*
*****************************************************************************
*/
/** Sources directory cluster */
#define VDISK_SOURCES_CLUSTER 4
/** Sources directory sector */
#define VDISK_SOURCES_SECTOR VDISK_CLUSTER_SECTOR ( VDISK_SOURCES_CLUSTER )
/** Sources directory LBA */
#define VDISK_SOURCES_LBA ( VDISK_VBR_LBA + VDISK_SOURCES_SECTOR )
/*****************************************************************************
*
* Fonts directory
*
*****************************************************************************
*/
/** Fonts directory cluster */
#define VDISK_FONTS_CLUSTER 5
/** Fonts directory sector */
#define VDISK_FONTS_SECTOR VDISK_CLUSTER_SECTOR ( VDISK_FONTS_CLUSTER )
/** Fonts directory LBA */
#define VDISK_FONTS_LBA ( VDISK_VBR_LBA + VDISK_FONTS_SECTOR )
/*****************************************************************************
*
* Resources directory
*
*****************************************************************************
*/
/** Resources directory cluster */
#define VDISK_RESOURCES_CLUSTER 6
/** Resources directory sector */
#define VDISK_RESOURCES_SECTOR VDISK_CLUSTER_SECTOR ( VDISK_RESOURCES_CLUSTER )
/** Resources directory LBA */
#define VDISK_RESOURCES_LBA ( VDISK_VBR_LBA + VDISK_RESOURCES_SECTOR )
/*****************************************************************************
*
* EFI directory
*
*****************************************************************************
*/
/** EFI directory cluster */
#define VDISK_EFI_CLUSTER 7
/** EFI directory sector */
#define VDISK_EFI_SECTOR VDISK_CLUSTER_SECTOR ( VDISK_EFI_CLUSTER )
/** EFI directory LBA */
#define VDISK_EFI_LBA ( VDISK_VBR_LBA + VDISK_EFI_SECTOR )
/*****************************************************************************
*
* Microsoft directory
*
*****************************************************************************
*/
/** Microsoft directory cluster */
#define VDISK_MICROSOFT_CLUSTER 8
/** Microsoft directory sector */
#define VDISK_MICROSOFT_SECTOR VDISK_CLUSTER_SECTOR ( VDISK_MICROSOFT_CLUSTER )
/** Microsoft directory LBA */
#define VDISK_MICROSOFT_LBA ( VDISK_VBR_LBA + VDISK_MICROSOFT_SECTOR )
/*****************************************************************************
*
* Files
*
*****************************************************************************
*/
/** Maximum virtual filename length (excluding NUL) */
#define VDISK_NAME_LEN 31
/** A virtual file */
struct vdisk_file {
/** Filename */
char name[ VDISK_NAME_LEN + 1 /* NUL */ ];
/** Opaque token */
void *opaque;
/** Length (excluding any zero-padding) */
size_t len;
/** Length (including any zero-padding) */
size_t xlen;
/** Read data
*
* @v file Virtual file
* @v data Data buffer
* @v offset Starting offset
* @v len Length
*/
void ( * read ) ( struct vdisk_file *file, void *data, size_t offset,
size_t len );
/** Patch data (optional)
*
* @v file Virtual file
* @v data Data buffer
* @v offset Starting offset
* @v len Length
*/
void ( * patch ) ( struct vdisk_file *file, void *data, size_t offset,
size_t len );
};
extern struct vdisk_file vdisk_files[VDISK_MAX_FILES];
extern void vdisk_read ( uint64_t lba, unsigned int count, void *data );
extern struct vdisk_file *
vdisk_add_file ( const char *name, void *opaque, size_t len,
void ( * read ) ( struct vdisk_file *file, void *data,
size_t offset, size_t len ) );
extern void
vdisk_patch_file ( struct vdisk_file *file,
void ( * patch ) ( struct vdisk_file *file, void *data,
size_t offset, size_t len ) );
#endif /* _VDISK_H */
| 16,379 |
C
|
.h
| 514 | 29.90856 | 79 | 0.599772 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
979 |
stdint.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/stdint.h
|
#ifndef _STDINT_H
#define _STDINT_H
/*
* Copyright (C) 2012 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* Standard integer types
*
*/
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef unsigned long long uint64_t;
typedef signed char int8_t;
typedef signed short int16_t;
typedef signed int int32_t;
typedef signed long long int64_t;
typedef unsigned long intptr_t;
typedef __SIZE_TYPE__ size_t;
typedef signed long ssize_t;
typedef __WCHAR_TYPE__ wchar_t;
typedef __WINT_TYPE__ wint_t;
#endif /* _STDINT_H */
| 1,315 |
C
|
.h
| 40 | 31.125 | 70 | 0.760852 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
980 |
wim.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/wim.h
|
#ifndef _WIM_H
#define _WIM_H
/*
* Copyright (C) 2014 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* WIM images
*
* The file format is documented in the document "Windows Imaging File
* Format (WIM)", available from
*
* http://www.microsoft.com/en-us/download/details.aspx?id=13096
*
* The wimlib source code is also a useful reference.
*
*/
#include <stdint.h>
/** A WIM resource header */
struct wim_resource_header {
/** Compressed length and flags */
uint64_t zlen__flags;
/** Offset */
uint64_t offset;
/** Uncompressed length */
uint64_t len;
} __attribute__ (( packed ));
/** WIM resource header length mask */
#define WIM_RESHDR_ZLEN_MASK 0x00ffffffffffffffULL
/** WIM resource header flags */
enum wim_resource_header_flags {
/** Resource contains metadata */
WIM_RESHDR_METADATA = ( 0x02ULL << 56 ),
/** Resource is compressed */
WIM_RESHDR_COMPRESSED = ( 0x04ULL << 56 ),
/** Resource is compressed using packed streams */
WIM_RESHDR_PACKED_STREAMS = ( 0x10ULL << 56 ),
};
/** A WIM header */
struct wim_header {
/** Signature */
uint8_t signature[8];
/** Header length */
uint32_t header_len;
/** Verson */
uint32_t version;
/** Flags */
uint32_t flags;
/** Chunk length */
uint32_t chunk_len;
/** GUID */
uint8_t guid[16];
/** Part number */
uint16_t part;
/** Total number of parts */
uint16_t parts;
/** Number of images */
uint32_t images;
/** Lookup table */
struct wim_resource_header lookup;
/** XML data */
struct wim_resource_header xml;
/** Boot metadata */
struct wim_resource_header boot;
/** Boot index */
uint32_t boot_index;
/** Integrity table */
struct wim_resource_header integrity;
/** Reserved */
uint8_t reserved[60];
} __attribute__ (( packed ));;
/** WIM header flags */
enum wim_header_flags {
/** WIM uses Xpress compresson */
WIM_HDR_XPRESS = 0x00020000,
/** WIM uses LZX compression */
WIM_HDR_LZX = 0x00040000,
};
/** A WIM file hash */
struct wim_hash {
/** SHA-1 hash */
uint8_t sha1[20];
} __attribute__ (( packed ));
/** A WIM lookup table entry */
struct wim_lookup_entry {
/** Resource header */
struct wim_resource_header resource;
/** Part number */
uint16_t part;
/** Reference count */
uint32_t refcnt;
/** Hash */
struct wim_hash hash;
} __attribute__ (( packed ));
/** WIM chunk length */
#define WIM_CHUNK_LEN 32768
/** A WIM chunk buffer */
struct wim_chunk_buffer {
/** Data */
uint8_t data[WIM_CHUNK_LEN];
};
/** Security data */
struct wim_security_header {
/** Length */
uint32_t len;
/** Number of entries */
uint32_t count;
} __attribute__ (( packed ));
/** Directory entry */
struct wim_directory_entry {
/** Length */
uint64_t len;
/** Attributes */
uint32_t attributes;
/** Security ID */
uint32_t security;
/** Subdirectory offset */
uint64_t subdir;
/** Reserved */
uint8_t reserved1[16];
/** Creation time */
uint64_t created;
/** Last access time */
uint64_t accessed;
/** Last written time */
uint64_t written;
/** Hash */
struct wim_hash hash;
/** Reserved */
uint8_t reserved2[12];
/** Streams */
uint16_t streams;
/** Short name length */
uint16_t short_name_len;
/** Name length */
uint16_t name_len;
} __attribute__ (( packed ));
/** Normal file */
#define WIM_ATTR_NORMAL 0x00000080UL
/** No security information exists for this file */
#define WIM_NO_SECURITY 0xffffffffUL
/** Windows complains if the time fields are left at zero */
#define WIM_MAGIC_TIME 0x1a7b83d2ad93000ULL
extern int wim_header ( struct vdisk_file *file, struct wim_header *header );
extern int wim_count ( struct vdisk_file *file, struct wim_header *header,
unsigned int *count );
extern int wim_metadata ( struct vdisk_file *file, struct wim_header *header,
unsigned int index, struct wim_resource_header *meta);
extern int wim_read ( struct vdisk_file *file, struct wim_header *header,
struct wim_resource_header *resource, void *data,
size_t offset, size_t len );
extern int wim_path ( struct vdisk_file *file, struct wim_header *header,
struct wim_resource_header *meta, const wchar_t *path,
size_t *offset, struct wim_directory_entry *direntry );
extern int wim_file ( struct vdisk_file *file, struct wim_header *header,
struct wim_resource_header *meta, const wchar_t *path,
struct wim_resource_header *resource );
extern int wim_dir_len ( struct vdisk_file *file, struct wim_header *header,
struct wim_resource_header *meta, size_t offset,
size_t *len );
#endif /* _WIM_H */
| 5,261 |
C
|
.h
| 177 | 27.553672 | 77 | 0.697335 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
982 |
lzx.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/lzx.h
|
#ifndef _LZX_H
#define _LZX_H
/*
* Copyright (C) 2014 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* LZX decompression
*
*/
#include <stdint.h>
#include "huffman.h"
/** Number of aligned offset codes */
#define LZX_ALIGNOFFSET_CODES 8
/** Aligned offset code length (in bits) */
#define LZX_ALIGNOFFSET_BITS 3
/** Number of pretree codes */
#define LZX_PRETREE_CODES 20
/** Pretree code length (in bits) */
#define LZX_PRETREE_BITS 4
/** Number of literal main codes */
#define LZX_MAIN_LIT_CODES 256
/** Number of position slots */
#define LZX_POSITION_SLOTS 30
/** Number of main codes */
#define LZX_MAIN_CODES ( LZX_MAIN_LIT_CODES + ( 8 * LZX_POSITION_SLOTS ) )
/** Number of length codes */
#define LZX_LENGTH_CODES 249
/** Block type length (in bits) */
#define LZX_BLOCK_TYPE_BITS 3
/** Default block length */
#define LZX_DEFAULT_BLOCK_LEN 32768
/** Number of repeated offsets */
#define LZX_REPEATED_OFFSETS 3
/** Don't ask */
#define LZX_WIM_MAGIC_FILESIZE 12000000
/** Block types */
enum lzx_block_type {
/** Verbatim block */
LZX_BLOCK_VERBATIM = 1,
/** Aligned offset block */
LZX_BLOCK_ALIGNOFFSET = 2,
/** Uncompressed block */
LZX_BLOCK_UNCOMPRESSED = 3,
};
/** An LZX input stream */
struct lzx_input_stream {
/** Data */
const uint8_t *data;
/** Length */
size_t len;
/** Offset within stream */
size_t offset;
};
/** An LZX output stream */
struct lzx_output_stream {
/** Data, or NULL */
uint8_t *data;
/** Offset within stream */
size_t offset;
/** End of current block within stream */
size_t threshold;
};
/** LZX decompressor */
struct lzx {
/** Input stream */
struct lzx_input_stream input;
/** Output stream */
struct lzx_output_stream output;
/** Accumulator */
uint32_t accumulator;
/** Number of bits in accumulator */
unsigned int bits;
/** Block type */
enum lzx_block_type block_type;
/** Repeated offsets */
unsigned int repeated_offset[LZX_REPEATED_OFFSETS];
/** Aligned offset Huffman alphabet */
struct huffman_alphabet alignoffset;
/** Aligned offset raw symbols
*
* Must immediately follow the aligned offset Huffman
* alphabet.
*/
huffman_raw_symbol_t alignoffset_raw[LZX_ALIGNOFFSET_CODES];
/** Aligned offset code lengths */
uint8_t alignoffset_lengths[LZX_ALIGNOFFSET_CODES];
/** Pretree Huffman alphabet */
struct huffman_alphabet pretree;
/** Pretree raw symbols
*
* Must immediately follow the pretree Huffman alphabet.
*/
huffman_raw_symbol_t pretree_raw[LZX_PRETREE_CODES];
/** Preetree code lengths */
uint8_t pretree_lengths[LZX_PRETREE_CODES];
/** Main Huffman alphabet */
struct huffman_alphabet main;
/** Main raw symbols
*
* Must immediately follow the main Huffman alphabet.
*/
huffman_raw_symbol_t main_raw[LZX_MAIN_CODES];
/** Main code lengths */
struct {
/** Literals */
uint8_t literals[LZX_MAIN_LIT_CODES];
/** Remaining symbols */
uint8_t remainder[ LZX_MAIN_CODES - LZX_MAIN_LIT_CODES ];
} __attribute__ (( packed )) main_lengths;
/** Length Huffman alphabet */
struct huffman_alphabet length;
/** Length raw symbols
*
* Must immediately follow the length Huffman alphabet.
*/
huffman_raw_symbol_t length_raw[LZX_LENGTH_CODES];
/** Length code lengths */
uint8_t length_lengths[LZX_LENGTH_CODES];
};
/**
* Calculate number of footer bits for a given position slot
*
* @v position_slot Position slot
* @ret footer_bits Number of footer bits
*/
static inline unsigned int lzx_footer_bits ( unsigned int position_slot ) {
if ( position_slot < 2 ) {
return 0;
} else if ( position_slot < 38 ) {
return ( ( position_slot / 2 ) - 1 );
} else {
return 17;
}
}
extern ssize_t lzx_decompress ( const void *data, size_t len, void *buf );
#endif /* _LZX_H */
| 4,488 |
C
|
.h
| 153 | 27.333333 | 75 | 0.71727 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
984 |
sha1.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/sha1.h
|
#ifndef _SHA1_H
#define _SHA1_H
/** @file
*
* SHA-1 algorithm
*
*/
#include <stdint.h>
/** An SHA-1 digest */
struct sha1_digest {
/** Hash output */
uint32_t h[5];
};
/** An SHA-1 data block */
union sha1_block {
/** Raw bytes */
uint8_t byte[64];
/** Raw dwords */
uint32_t dword[16];
/** Final block structure */
struct {
/** Padding */
uint8_t pad[56];
/** Length in bits */
uint64_t len;
} final;
};
/** SHA-1 digest and data block
*
* The order of fields within this structure is designed to minimise
* code size.
*/
struct sha1_digest_data {
/** Digest of data already processed */
struct sha1_digest digest;
/** Accumulated data */
union sha1_block data;
} __attribute__ (( packed ));
/** SHA-1 digest and data block */
union sha1_digest_data_dwords {
/** Digest and data block */
struct sha1_digest_data dd;
/** Raw dwords */
uint32_t dword[ sizeof ( struct sha1_digest_data ) /
sizeof ( uint32_t ) ];
};
/** An SHA-1 context */
struct sha1_context {
/** Amount of accumulated data */
size_t len;
/** Digest and accumulated data */
union sha1_digest_data_dwords ddd;
} __attribute__ (( packed ));
/** SHA-1 context size */
#define SHA1_CTX_SIZE sizeof ( struct sha1_context )
/** SHA-1 digest size */
#define SHA1_DIGEST_SIZE sizeof ( struct sha1_digest )
extern void sha1_init ( void *ctx );
extern void sha1_update ( void *ctx, const void *data, size_t len );
extern void sha1_final ( void *ctx, void *out );
#endif /* _SHA1_H */
| 1,492 |
C
|
.h
| 61 | 22.622951 | 68 | 0.666901 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
987 |
stddef.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/stddef.h
|
#ifndef _STDDEF_H
#define _STDDEF_H
/*
* Copyright (C) 2012 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* Standard definitions
*
*/
#include <stdint.h>
#define NULL ( ( void * ) 0 )
#define offsetof( type, member ) ( ( size_t ) &( ( type * ) NULL )->member )
#define container_of( ptr, type, member ) ( { \
const typeof ( ( ( type * ) NULL )->member ) *__mptr = (ptr); \
( type * ) ( ( void * ) __mptr - offsetof ( type, member ) ); } )
#endif /* _STDDEF_H */
| 1,217 |
C
|
.h
| 33 | 34.939394 | 76 | 0.691589 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
988 |
assert.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/assert.h
|
#ifndef _ASSERT_H
#define _ASSERT_H
/*
* Copyright (C) 2014 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* Assertions
*
*/
#include "wimboot.h"
#define assert(x) do { \
if ( DEBUG && ! (x) ) { \
die ( "Assertion failed at %s line %d: %s\n", \
__FILE__, __LINE__, #x ); \
} \
} while ( 0 )
#endif /* _ASSERT_H */
| 1,091 |
C
|
.h
| 34 | 29.911765 | 70 | 0.686312 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
989 |
cmdline.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/cmdline.h
|
#ifndef _CMDLINE_H
#define _CMDLINE_H
/*
* Copyright (C) 2014 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* Command line
*
*/
extern int cmdline_rawbcd;
extern int cmdline_rawwim;
extern int cmdline_quiet;
extern int cmdline_gui;
extern int cmdline_pause;
extern int cmdline_pause_quiet;
extern int cmdline_linear;
extern unsigned int cmdline_index;
extern void process_cmdline ( char *cmdline );
typedef int (*file_size_pf)(const char *path);
typedef int (*file_read_pf)(const char *path, int offset, int len, void *buf);
extern file_size_pf pfventoy_file_size;
extern file_read_pf pfventoy_file_read;
#define MAX_VF 16
extern char cmdline_vf_path[MAX_VF][64];
extern int cmdline_vf_num;
#endif /* _CMDLINE_H */
| 1,463 |
C
|
.h
| 43 | 32.395349 | 78 | 0.761837 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
990 |
efiboot.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/efiboot.h
|
#ifndef _EFIBOOT_H
#define _EFIBOOT_H
/*
* Copyright (C) 2014 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* EFI boot manager invocation
*
*/
#include "efi.h"
#include "efi/Protocol/DevicePath.h"
struct vdisk_file;
extern void efi_boot ( struct vdisk_file *file, EFI_DEVICE_PATH_PROTOCOL *path,
EFI_HANDLE device );
#endif /* _EFIBOOT_H */
| 1,099 |
C
|
.h
| 32 | 32.1875 | 79 | 0.743638 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
991 |
pause.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/pause.h
|
#ifndef _PAUSE_H
#define _PAUSE_H
/*
* Copyright (C) 2014 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* Diagnostic pause
*
*/
extern void pause ( void );
#endif /* _PAUSE_H */
| 925 |
C
|
.h
| 28 | 31.107143 | 70 | 0.741321 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
992 |
efi.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/efi.h
|
#ifndef _EFI_H
#define _EFI_H
/*
* Copyright (C) 2014 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* EFI definitions
*
*/
/* EFIAPI definition */
#if __x86_64__
#define EFIAPI __attribute__ (( ms_abi ))
#else
#define EFIAPI
#endif
/* EFI headers rudely redefine NULL */
#undef NULL
#include "efi/Uefi.h"
#include "efi/Protocol/LoadedImage.h"
extern EFI_SYSTEM_TABLE *efi_systab;
extern EFI_HANDLE efi_image_handle;
extern EFI_GUID efi_block_io_protocol_guid;
extern EFI_GUID efi_device_path_protocol_guid;
extern EFI_GUID efi_graphics_output_protocol_guid;
extern EFI_GUID efi_loaded_image_protocol_guid;
extern EFI_GUID efi_simple_file_system_protocol_guid;
#endif /* _EFI_H */
| 1,431 |
C
|
.h
| 44 | 30.840909 | 70 | 0.75707 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
994 |
paging.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/paging.h
|
#ifndef _PAGING_H
#define _PAGING_H
/*
* Copyright (C) 2021 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* Paging
*
*/
#include <stddef.h>
/** Get CPU features */
#define CPUID_FEATURES 0x00000001
/** CPU supports PAE */
#define CPUID_FEATURE_EDX_PAE 0x00000040
/* CR0: paging */
#define CR0_PG 0x80000000
/* CR4: physical address extensions */
#define CR4_PAE 0x00000020
/* Page: present */
#define PG_P 0x01
/* Page: read/write */
#define PG_RW 0x02
/* Page: user/supervisor */
#define PG_US 0x04
/* Page: page size */
#define PG_PS 0x80
/** 2MB page size */
#define PAGE_SIZE_2MB 0x200000
/** 32-bit address space size */
#define ADDR_4GB 0x100000000ULL
/** Saved paging state */
struct paging_state {
/** Control register 0 */
unsigned long cr0;
/** Control register 3 */
unsigned long cr3;
/** Control register 4 */
unsigned long cr4;
};
extern int paging;
extern void init_paging ( void );
extern void enable_paging ( struct paging_state *state );
extern void disable_paging ( struct paging_state *state );
extern uint64_t relocate_memory_high ( void *start, size_t len );
#endif /* _PAGING_H */
| 1,869 |
C
|
.h
| 62 | 28.419355 | 70 | 0.735754 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
995 |
efifile.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/efifile.h
|
#ifndef _EFIFILE_H
#define _EFIFILE_H
/*
* Copyright (C) 2014 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* EFI file system access
*
*/
#include "efi.h"
#include "efi/Protocol/SimpleFileSystem.h"
#include "efi/Guid/FileInfo.h"
struct vdisk_file;
extern struct vdisk_file *bootmgfw;
extern void efi_extract ( EFI_HANDLE handle );
#endif /* _EFIFILE_H */
| 1,104 |
C
|
.h
| 33 | 31.606061 | 70 | 0.752113 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
999 |
int13.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/int13.h
|
#ifndef _INT13_H
#define _INT13_H
/*
* Copyright (C) 2012 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* INT 13 emulation
*
*/
/** Construct a pointer from a real-mode segment:offset address */
#define REAL_PTR( segment, offset ) \
( ( void * ) ( intptr_t ) ( ( (segment) << 4 ) + offset ) )
/** Get drive parameters */
#define INT13_GET_PARAMETERS 0x08
/** Get disk type */
#define INT13_GET_DISK_TYPE 0x15
/** Extensions installation check */
#define INT13_EXTENSION_CHECK 0x41
/** Extended read */
#define INT13_EXTENDED_READ 0x42
/** Get extended drive parameters */
#define INT13_GET_EXTENDED_PARAMETERS 0x48
/** Operation completed successfully */
#define INT13_STATUS_SUCCESS 0x00
/** Invalid function or parameter */
#define INT13_STATUS_INVALID 0x01
/** Read error */
#define INT13_STATUS_READ_ERROR 0x04
/** Reset failed */
#define INT13_STATUS_RESET_FAILED 0x05
/** Write error */
#define INT13_STATUS_WRITE_ERROR 0xcc
/** No such drive */
#define INT13_DISK_TYPE_NONE 0x00
/** Floppy without change-line support */
#define INT13_DISK_TYPE_FDD 0x01
/** Floppy with change-line support */
#define INT13_DISK_TYPE_FDD_CL 0x02
/** Hard disk */
#define INT13_DISK_TYPE_HDD 0x03
/** Extended disk access functions supported */
#define INT13_EXTENSION_LINEAR 0x01
/** INT13 extensions version 1.x */
#define INT13_EXTENSION_VER_1_X 0x01
/** DMA boundary errors handled transparently */
#define INT13_FL_DMA_TRANSPARENT 0x01
/** BIOS drive counter */
#define INT13_DRIVE_COUNT ( *( ( ( uint8_t * ) REAL_PTR ( 0x40, 0x75 ) ) ) )
/** An INT 13 disk address packet */
struct int13_disk_address {
/** Size of the packet, in bytes */
uint8_t bufsize;
/** Reserved */
uint8_t reserved_a;
/** Block count */
uint8_t count;
/** Reserved */
uint8_t reserved_b;
/** Data buffer */
struct segoff buffer;
/** Starting block number */
uint64_t lba;
/** Data buffer (EDD 3.0+ only) */
uint64_t buffer_phys;
/** Block count (EDD 4.0+ only) */
uint32_t long_count;
/** Reserved */
uint32_t reserved_c;
} __attribute__ (( packed ));
/** INT 13 disk parameters */
struct int13_disk_parameters {
/** Size of this structure */
uint16_t bufsize;
/** Flags */
uint16_t flags;
/** Number of cylinders */
uint32_t cylinders;
/** Number of heads */
uint32_t heads;
/** Number of sectors per track */
uint32_t sectors_per_track;
/** Total number of sectors on drive */
uint64_t sectors;
/** Bytes per sector */
uint16_t sector_size;
} __attribute__ (( packed ));
extern int initialise_int13 ( void );
extern void emulate_int13 ( struct bootapp_callback_params *params );
#endif /* _INT13_H */
| 3,376 |
C
|
.h
| 106 | 30.198113 | 76 | 0.714988 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
1,000 |
wimfile.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/wimfile.h
|
#ifndef _WIMFILE_H
#define _WIMFILE_H
/*
* Copyright (C) 2014 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* WIM virtual files
*
*/
#include <wchar.h>
struct vdisk_file;
extern struct vdisk_file * wim_add_file ( struct vdisk_file *file,
unsigned int index,
const wchar_t *path,
const wchar_t *wname );
extern void wim_add_files ( struct vdisk_file *file, unsigned int index,
const wchar_t **paths );
#endif /* _WIMFILE_H */
| 1,202 |
C
|
.h
| 35 | 31.742857 | 72 | 0.728682 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
1,004 |
bootapp.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/bootapp.h
|
#ifndef _BOOTAPP_H
#define _BOOTAPP_H
/*
* Copyright (C) 2012 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* Boot application data structures
*
*/
#include <stdint.h>
/** A segment:offset address */
struct segoff {
/** Offset */
uint16_t offset;
/** Segment */
uint16_t segment;
} __attribute__ (( packed ));
/** A GUID */
struct guid {
/** 8 hex digits, big-endian */
uint32_t a;
/** 2 hex digits, big-endian */
uint16_t b;
/** 2 hex digits, big-endian */
uint16_t c;
/** 2 hex digits, big-endian */
uint16_t d;
/** 12 hex digits, big-endian */
uint8_t e[6];
} __attribute__ (( packed ));
/** Real-mode callback parameters */
struct bootapp_callback_params {
/** Vector */
union {
/** Interrupt number */
uint32_t interrupt;
/** Segment:offset address of real-mode function */
struct segoff function;
} vector;
/** %eax value */
union {
struct {
uint8_t al;
uint8_t ah;
} __attribute__ (( packed ));
uint16_t ax;
uint32_t eax;
};
/** %ebx value */
union {
struct {
uint8_t bl;
uint8_t bh;
} __attribute__ (( packed ));
uint16_t bx;
uint32_t ebx;
};
/** %ecx value */
union {
struct {
uint8_t cl;
uint8_t ch;
} __attribute__ (( packed ));
uint16_t cx;
uint32_t ecx;
};
/** %edx value */
union {
struct {
uint8_t dl;
uint8_t dh;
} __attribute__ (( packed ));
uint16_t dx;
uint32_t edx;
};
/** Placeholder (for %esp?) */
uint32_t unused_esp;
/** Placeholder (for %ebp?) */
uint32_t unused_ebp;
/** %esi value */
union {
uint16_t si;
uint32_t esi;
};
/** %edi value */
union {
uint16_t di;
uint32_t edi;
};
/** Placeholder (for %cs?) */
uint32_t unused_cs;
/** %ds value */
uint32_t ds;
/** Placeholder (for %ss?) */
uint32_t unused_ss;
/** %es value */
uint32_t es;
/** %fs value */
uint32_t fs;
/** %gs value */
uint32_t gs;
/** eflags value */
uint32_t eflags;
} __attribute__ (( packed ));
/** eflags bits */
enum eflags {
CF = ( 1 << 0 ),
PF = ( 1 << 2 ),
AF = ( 1 << 4 ),
ZF = ( 1 << 6 ),
SF = ( 1 << 7 ),
OF = ( 1 << 11 ),
};
/** Real-mode callback function table */
struct bootapp_callback_functions {
/**
* Call an arbitrary real-mode interrupt
*
* @v params Parameters
*/
void ( * call_interrupt ) ( struct bootapp_callback_params *params );
/**
* Call an arbitrary real-mode function
*
* @v params Parameters
*/
void ( * call_real ) ( struct bootapp_callback_params *params );
} __attribute__ (( packed ));
/** Real-mode callbacks */
struct bootapp_callback {
/** Real-mode callback function table */
struct bootapp_callback_functions *fns;
/** Drive number for INT13 calls */
uint32_t drive;
} __attribute__ (( packed ));
/** Boot application descriptor */
struct bootapp_descriptor {
/** Signature */
char signature[8];
/** Version */
uint32_t version;
/** Total length */
uint32_t len;
/** COFF machine type */
uint32_t arch;
/** Reserved */
uint32_t reserved_0x14;
/** Loaded PE image base address */
void *pe_base;
/** Reserved */
uint32_t reserved_0x1c;
/** Length of loaded PE image */
uint32_t pe_len;
/** Offset to memory descriptor */
uint32_t memory;
/** Offset to boot application entry descriptor */
uint32_t entry;
/** Offset to ??? */
uint32_t xxx;
/** Offset to callback descriptor */
uint32_t callback;
/** Offset to pointless descriptor */
uint32_t pointless;
/** Reserved */
uint32_t reserved_0x38;
} __attribute__ (( packed ));
/** "BOOT APP" magic signature */
#define BOOTAPP_SIGNATURE "BOOT APP"
/** Boot application descriptor version */
#define BOOTAPP_VERSION 2
/** i386 architecture */
#define BOOTAPP_ARCH_I386 0x014c
/** Memory region descriptor */
struct bootapp_memory_region {
/** Reserved (for struct list_head?) */
uint8_t reserved[8];
/** Start page address */
uint64_t start_page;
/** Reserved */
uint8_t reserved_0x10[8];
/** Number of pages */
uint64_t num_pages;
/** Reserved */
uint8_t reserved_0x20[4];
/** Flags */
uint32_t flags;
} __attribute__ (( packed ));
/** Memory descriptor */
struct bootapp_memory_descriptor {
/** Version */
uint32_t version;
/** Length of descriptor (excluding region descriptors) */
uint32_t len;
/** Number of regions */
uint32_t num_regions;
/** Length of each region descriptor */
uint32_t region_len;
/** Length of reserved area at start of each region descriptor */
uint32_t reserved_len;
} __attribute__ (( packed ));
/** Boot application memory descriptor version */
#define BOOTAPP_MEMORY_VERSION 1
/** Boot application entry descriptor */
struct bootapp_entry_descriptor {
/** Signature */
char signature[8];
/** Flags */
uint32_t flags;
/** GUID */
struct guid guid;
/** Reserved */
uint8_t reserved[16];
} __attribute__ (( packed ));
/** ??? */
struct bootapp_entry_wtf1_descriptor {
/** Flags */
uint32_t flags;
/** Length of descriptor */
uint32_t len;
/** Total length of following descriptors within BTAPENT */
uint32_t extra_len;
/** Reserved */
uint8_t reserved[12];
} __attribute__ (( packed ));
/** ??? */
struct bootapp_entry_wtf2_descriptor {
/** GUID */
struct guid guid;
} __attribute__ (( packed ));
/** ??? */
struct bootapp_entry_wtf3_descriptor {
/** Flags */
uint32_t flags;
/** Reserved */
uint32_t reserved_0x04;
/** Length of descriptor */
uint32_t len;
/** Reserved */
uint32_t reserved_0x0c;
/** Boot partition offset (in bytes) */
uint32_t boot_partition_offset;
/** Reserved */
uint8_t reserved_0x14[16];
/** MBR signature present? */
uint32_t xxx;
/** MBR signature */
uint32_t mbr_signature;
/** Reserved */
uint8_t reserved_0x2c[26];
} __attribute__ (( packed ));
/** "BTAPENT" magic signature */
#define BOOTAPP_ENTRY_SIGNATURE "BTAPENT\0"
/** Boot application entry flags
*
* pxeboot, etftboot, and fatboot all use a value of 0x21; I have no
* idea what it means.
*/
#define BOOTAPP_ENTRY_FLAGS 0x21
/** Boot application callback descriptor */
struct bootapp_callback_descriptor {
/** Real-mode callbacks */
struct bootapp_callback *callback;
/** Reserved */
uint32_t reserved;
} __attribute__ (( packed ));
/** Boot application pointless descriptor */
struct bootapp_pointless_descriptor {
/** Version */
uint32_t version;
/** Reserved */
uint8_t reserved[24];
} __attribute__ (( packed ));
/** Boot application pointless descriptor version */
#define BOOTAPP_POINTLESS_VERSION 1
#endif /* _BOOTAPP_H */
| 7,150 |
C
|
.h
| 292 | 22.455479 | 70 | 0.668179 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
1,006 |
huffman.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/huffman.h
|
#ifndef _HUFFMAN_H
#define _HUFFMAN_H
/*
* Copyright (C) 2014 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* Huffman alphabets
*
*/
#include <stdint.h>
/** Maximum length of a Huffman symbol (in bits) */
#define HUFFMAN_BITS 16
/** Raw huffman symbol */
typedef uint16_t huffman_raw_symbol_t;
/** Quick lookup length for a Huffman symbol (in bits)
*
* This is a policy decision.
*/
#define HUFFMAN_QL_BITS 7
/** Quick lookup shift */
#define HUFFMAN_QL_SHIFT ( HUFFMAN_BITS - HUFFMAN_QL_BITS )
/** A Huffman-coded set of symbols of a given length */
struct huffman_symbols {
/** Length of Huffman-coded symbols (in bits) */
uint8_t bits;
/** Shift to normalise symbols of this length to HUFFMAN_BITS bits */
uint8_t shift;
/** Number of Huffman-coded symbols having this length */
uint16_t freq;
/** First symbol of this length (normalised to HUFFMAN_BITS bits)
*
* Stored as a 32-bit value to allow the value
* (1<<HUFFMAN_BITS ) to be used for empty sets of symbols
* longer than the maximum utilised length.
*/
uint32_t start;
/** Raw symbols having this length */
huffman_raw_symbol_t *raw;
};
/** A Huffman-coded alphabet */
struct huffman_alphabet {
/** Huffman-coded symbol set for each length */
struct huffman_symbols huf[HUFFMAN_BITS];
/** Quick lookup table */
uint8_t lookup[ 1 << HUFFMAN_QL_BITS ];
/** Raw symbols
*
* Ordered by Huffman-coded symbol length, then by symbol
* value. This field has a variable length.
*/
huffman_raw_symbol_t raw[0];
};
/**
* Get Huffman symbol length
*
* @v sym Huffman symbol set
* @ret len Length (in bits)
*/
static inline __attribute__ (( always_inline )) unsigned int
huffman_len ( struct huffman_symbols *sym ) {
return sym->bits;
}
/**
* Get Huffman symbol value
*
* @v sym Huffman symbol set
* @v huf Raw input value (normalised to HUFFMAN_BITS bits)
* @ret raw Raw symbol value
*/
static inline __attribute__ (( always_inline )) huffman_raw_symbol_t
huffman_raw ( struct huffman_symbols *sym, unsigned int huf ) {
return sym->raw[ huf >> sym->shift ];
}
extern int huffman_alphabet ( struct huffman_alphabet *alphabet,
uint8_t *lengths, unsigned int count );
extern struct huffman_symbols *
huffman_sym ( struct huffman_alphabet *alphabet, unsigned int huf );
#endif /* _HUFFMAN_H */
| 3,063 |
C
|
.h
| 95 | 30.231579 | 70 | 0.724009 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
1,007 |
byteswap.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/byteswap.h
|
#ifndef _BITS_BYTESWAP_H
#define _BITS_BYTESWAP_H
/** @file
*
* Byte-order swapping functions
*
*/
#include <stdint.h>
static inline __attribute__ (( always_inline, const )) uint16_t
__bswap_variable_16 ( uint16_t x ) {
__asm__ ( "xchgb %b0,%h0" : "=Q" ( x ) : "0" ( x ) );
return x;
}
static inline __attribute__ (( always_inline )) void
__bswap_16s ( uint16_t *x ) {
__asm__ ( "rorw $8, %0" : "+m" ( *x ) );
}
static inline __attribute__ (( always_inline, const )) uint32_t
__bswap_variable_32 ( uint32_t x ) {
__asm__ ( "bswapl %k0" : "=r" ( x ) : "0" ( x ) );
return x;
}
static inline __attribute__ (( always_inline )) void
__bswap_32s ( uint32_t *x ) {
__asm__ ( "bswapl %k0" : "=r" ( *x ) : "0" ( *x ) );
}
#ifdef __x86_64__
static inline __attribute__ (( always_inline, const )) uint64_t
__bswap_variable_64 ( uint64_t x ) {
__asm__ ( "bswapq %q0" : "=r" ( x ) : "0" ( x ) );
return x;
}
#else /* __x86_64__ */
static inline __attribute__ (( always_inline, const )) uint64_t
__bswap_variable_64 ( uint64_t x ) {
uint32_t in_high = ( x >> 32 );
uint32_t in_low = ( x & 0xffffffffUL );
uint32_t out_high;
uint32_t out_low;
__asm__ ( "bswapl %0\n\t"
"bswapl %1\n\t"
"xchgl %0,%1\n\t"
: "=r" ( out_high ), "=r" ( out_low )
: "0" ( in_high ), "1" ( in_low ) );
return ( ( ( ( uint64_t ) out_high ) << 32 ) |
( ( uint64_t ) out_low ) );
}
#endif /* __x86_64__ */
static inline __attribute__ (( always_inline )) void
__bswap_64s ( uint64_t *x ) {
*x = __bswap_variable_64 ( *x );
}
/**
* Byte-swap a 16-bit constant
*
* @v value Constant value
* @ret swapped Byte-swapped value
*/
#define __bswap_constant_16( value ) \
( ( ( (value) & 0x00ff ) << 8 ) | \
( ( (value) & 0xff00 ) >> 8 ) )
/**
* Byte-swap a 32-bit constant
*
* @v value Constant value
* @ret swapped Byte-swapped value
*/
#define __bswap_constant_32( value ) \
( ( ( (value) & 0x000000ffUL ) << 24 ) | \
( ( (value) & 0x0000ff00UL ) << 8 ) | \
( ( (value) & 0x00ff0000UL ) >> 8 ) | \
( ( (value) & 0xff000000UL ) >> 24 ) )
/**
* Byte-swap a 64-bit constant
*
* @v value Constant value
* @ret swapped Byte-swapped value
*/
#define __bswap_constant_64( value ) \
( ( ( (value) & 0x00000000000000ffULL ) << 56 ) | \
( ( (value) & 0x000000000000ff00ULL ) << 40 ) | \
( ( (value) & 0x0000000000ff0000ULL ) << 24 ) | \
( ( (value) & 0x00000000ff000000ULL ) << 8 ) | \
( ( (value) & 0x000000ff00000000ULL ) >> 8 ) | \
( ( (value) & 0x0000ff0000000000ULL ) >> 24 ) | \
( ( (value) & 0x00ff000000000000ULL ) >> 40 ) | \
( ( (value) & 0xff00000000000000ULL ) >> 56 ) )
/**
* Byte-swap a 16-bit value
*
* @v value Value
* @ret swapped Byte-swapped value
*/
#define __bswap_16( value ) \
( __builtin_constant_p (value) ? \
( ( uint16_t ) __bswap_constant_16 ( ( uint16_t ) (value) ) ) \
: __bswap_variable_16 (value) )
#define bswap_16( value ) __bswap_16 (value)
/**
* Byte-swap a 32-bit value
*
* @v value Value
* @ret swapped Byte-swapped value
*/
#define __bswap_32( value ) \
( __builtin_constant_p (value) ? \
( ( uint32_t ) __bswap_constant_32 ( ( uint32_t ) (value) ) ) \
: __bswap_variable_32 (value) )
#define bswap_32( value ) __bswap_32 (value)
/**
* Byte-swap a 64-bit value
*
* @v value Value
* @ret swapped Byte-swapped value
*/
#define __bswap_64( value ) \
( __builtin_constant_p (value) ? \
( ( uint64_t ) __bswap_constant_64 ( ( uint64_t ) (value) ) ) \
: __bswap_variable_64 (value) )
#define bswap_64( value ) __bswap_64 (value)
#define __cpu_to_leNN( bits, value ) (value)
#define __cpu_to_beNN( bits, value ) __bswap_ ## bits (value)
#define __leNN_to_cpu( bits, value ) (value)
#define __beNN_to_cpu( bits, value ) __bswap_ ## bits (value)
#define __cpu_to_leNNs( bits, ptr ) do { } while ( 0 )
#define __cpu_to_beNNs( bits, ptr ) __bswap_ ## bits ## s (ptr)
#define __leNN_to_cpus( bits, ptr ) do { } while ( 0 )
#define __beNN_to_cpus( bits, ptr ) __bswap_ ## bits ## s (ptr)
#define cpu_to_le16( value ) __cpu_to_leNN ( 16, value )
#define cpu_to_le32( value ) __cpu_to_leNN ( 32, value )
#define cpu_to_le64( value ) __cpu_to_leNN ( 64, value )
#define cpu_to_be16( value ) __cpu_to_beNN ( 16, value )
#define cpu_to_be32( value ) __cpu_to_beNN ( 32, value )
#define cpu_to_be64( value ) __cpu_to_beNN ( 64, value )
#define le16_to_cpu( value ) __leNN_to_cpu ( 16, value )
#define le32_to_cpu( value ) __leNN_to_cpu ( 32, value )
#define le64_to_cpu( value ) __leNN_to_cpu ( 64, value )
#define be16_to_cpu( value ) __beNN_to_cpu ( 16, value )
#define be32_to_cpu( value ) __beNN_to_cpu ( 32, value )
#define be64_to_cpu( value ) __beNN_to_cpu ( 64, value )
#define cpu_to_le16s( ptr ) __cpu_to_leNNs ( 16, ptr )
#define cpu_to_le32s( ptr ) __cpu_to_leNNs ( 32, ptr )
#define cpu_to_le64s( ptr ) __cpu_to_leNNs ( 64, ptr )
#define cpu_to_be16s( ptr ) __cpu_to_beNNs ( 16, ptr )
#define cpu_to_be32s( ptr ) __cpu_to_beNNs ( 32, ptr )
#define cpu_to_be64s( ptr ) __cpu_to_beNNs ( 64, ptr )
#define le16_to_cpus( ptr ) __leNN_to_cpus ( 16, ptr )
#define le32_to_cpus( ptr ) __leNN_to_cpus ( 32, ptr )
#define le64_to_cpus( ptr ) __leNN_to_cpus ( 64, ptr )
#define be16_to_cpus( ptr ) __beNN_to_cpus ( 16, ptr )
#define be32_to_cpus( ptr ) __beNN_to_cpus ( 32, ptr )
#define be64_to_cpus( ptr ) __beNN_to_cpus ( 64, ptr )
#define htonll( value ) cpu_to_be64 (value)
#define ntohll( value ) be64_to_cpu (value)
#define htonl( value ) cpu_to_be32 (value)
#define ntohl( value ) be32_to_cpu (value)
#define htons( value ) cpu_to_be16 (value)
#define ntohs( value ) be16_to_cpu (value)
#endif /* _BITS_BYTESWAP_H */
| 5,710 |
C
|
.h
| 159 | 33.930818 | 66 | 0.589289 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
1,008 |
ctype.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/ctype.h
|
#ifndef _CTYPE_H
#define _CTYPE_H
/*
* Copyright (C) 2012 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* Character types
*
*/
static inline int islower ( int c ) {
return ( ( c >= 'a' ) && ( c <= 'z' ) );
}
static inline int isupper ( int c ) {
return ( ( c >= 'A' ) && ( c <= 'Z' ) );
}
static inline int toupper ( int c ) {
if ( islower ( c ) )
c -= ( 'a' - 'A' );
return c;
}
extern int isspace ( int c );
#endif /* _CTYPE_H */
| 1,189 |
C
|
.h
| 39 | 28.564103 | 70 | 0.683012 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
1,009 |
efipath.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/efipath.h
|
#ifndef _EFIPATH_H
#define _EFIPATH_H
/*
* Copyright (C) 2014 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* EFI device paths
*
*/
#include "efi.h"
#include "efi/Protocol/DevicePath.h"
/**
* Initialise device path
*
* @v name Variable name
* @v type Type
* @v subtype Subtype
*/
#define EFI_DEVPATH_INIT( name, type, subtype ) { \
.Type = (type), \
.SubType = (subtype), \
.Length[0] = ( sizeof (name) & 0xff ), \
.Length[1] = ( sizeof (name) >> 8 ), \
}
/**
* Initialise device path
*
* @v path Device path
* @v type Type
* @v subtype Subtype
* @v len Length
*/
static inline __attribute__ (( always_inline )) void
efi_devpath_init ( EFI_DEVICE_PATH_PROTOCOL *path, unsigned int type,
unsigned int subtype, size_t len ) {
path->Type = type;
path->SubType = subtype;
path->Length[0] = ( len & 0xff );
path->Length[1] = ( len >> 8 );
}
/**
* Initialise device path end
*
* @v name Variable name
*/
#define EFI_DEVPATH_END_INIT( name ) \
EFI_DEVPATH_INIT ( name, END_DEVICE_PATH_TYPE, \
END_ENTIRE_DEVICE_PATH_SUBTYPE )
/**
* Initialise device path end
*
* @v path Device path
*/
static inline __attribute__ (( always_inline )) void
efi_devpath_end_init ( EFI_DEVICE_PATH_PROTOCOL *path ) {
efi_devpath_init ( path, END_DEVICE_PATH_TYPE,
END_ENTIRE_DEVICE_PATH_SUBTYPE, sizeof ( *path ) );
}
extern EFI_DEVICE_PATH_PROTOCOL *
efi_devpath_end ( EFI_DEVICE_PATH_PROTOCOL *path );
#endif /* _EFIPATH_H */
| 2,231 |
C
|
.h
| 78 | 26.551282 | 70 | 0.688609 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
1,010 |
cpio.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/cpio.h
|
#ifndef _CPIO_H
#define _CPIO_H
/*
* Copyright (C) 2012 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* CPIO archives
*
*/
#include <stdint.h>
/** A CPIO archive header
*
* All field are hexadecimal ASCII numbers padded with '0' on the
* left to the full width of the field.
*/
struct cpio_header {
/** The string "070701" or "070702" */
char c_magic[6];
/** File inode number */
char c_ino[8];
/** File mode and permissions */
char c_mode[8];
/** File uid */
char c_uid[8];
/** File gid */
char c_gid[8];
/** Number of links */
char c_nlink[8];
/** Modification time */
char c_mtime[8];
/** Size of data field */
char c_filesize[8];
/** Major part of file device number */
char c_maj[8];
/** Minor part of file device number */
char c_min[8];
/** Major part of device node reference */
char c_rmaj[8];
/** Minor part of device node reference */
char c_rmin[8];
/** Length of filename, including final NUL */
char c_namesize[8];
/** Checksum of data field if c_magic is 070702, othersize zero */
char c_chksum[8];
} __attribute__ (( packed ));
/** CPIO magic */
#define CPIO_MAGIC "070701"
/** CPIO trailer */
#define CPIO_TRAILER "TRAILER!!!"
extern int cpio_extract ( void *data, size_t len,
int ( * file ) ( const char *name, void *data,
size_t len ) );
#endif /* _CPIO_H */
| 2,074 |
C
|
.h
| 70 | 27.557143 | 70 | 0.689379 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
1,013 |
Uefi.h
|
ventoy_Ventoy/wimboot/wimboot-2.7.3/src/efi/Uefi.h
|
/** @file
Root include file for Mde Package UEFI, UEFI_APPLICATION type modules.
This is the include file for any module of type UEFI and UEFI_APPLICATION. Uefi modules only use
types defined via this include file and can be ported easily to any
environment.
Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available under
the terms and conditions of the BSD License that accompanies this distribution.
The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#ifndef __PI_UEFI_H__
#define __PI_UEFI_H__
#include "efi/Uefi/UefiBaseType.h"
#include "efi/Uefi/UefiSpec.h"
#endif
| 871 |
C
|
.h
| 18 | 46.444444 | 98 | 0.792654 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
1,064 |
VentoyJson.h
|
ventoy_Ventoy/Ventoy2Disk/Ventoy2Disk/VentoyJson.h
|
/******************************************************************************
* VentoyJson.h
*
* Copyright (c) 2021, longpanda <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef __VENTOY_JSON_H__
#define __VENTOY_JSON_H__
#ifdef FOR_VTOY_JSON_CHECK
typedef unsigned char UINT8;
typedef unsigned short UINT16;
typedef unsigned int UINT32;
typedef unsigned long long UINT64;
#define Log printf
#define strcpy_s(a, b, c) strncpy(a, c, b)
#define sprintf_s snprintf
#endif
#define JSON_SUCCESS 0
#define JSON_FAILED 1
#define JSON_NOT_FOUND 2
typedef enum _JSON_TYPE
{
JSON_TYPE_NUMBER = 0,
JSON_TYPE_STRING,
JSON_TYPE_BOOL,
JSON_TYPE_ARRAY,
JSON_TYPE_OBJECT,
JSON_TYPE_NULL,
JSON_TYPE_BUTT
}JSON_TYPE;
typedef struct _VTOY_JSON
{
struct _VTOY_JSON *pstPrev;
struct _VTOY_JSON *pstNext;
struct _VTOY_JSON *pstChild;
JSON_TYPE enDataType;
union
{
char *pcStrVal;
int iNumVal;
UINT64 lValue;
}unData;
char *pcName;
}VTOY_JSON;
typedef struct _JSON_PARSE
{
char *pcKey;
void *pDataBuf;
UINT32 uiBufSize;
}JSON_PARSE;
#define JSON_NEW_ITEM(pstJson, ret) \
{ \
(pstJson) = (VTOY_JSON *)malloc(sizeof(VTOY_JSON)); \
if (NULL == (pstJson)) \
{ \
Log("Failed to alloc memory for json.\n"); \
return (ret); \
} \
memset((pstJson), 0, sizeof(VTOY_JSON));\
}
VTOY_JSON *vtoy_json_find_item
(
VTOY_JSON *pstJson,
JSON_TYPE enDataType,
const char *szKey
);
int vtoy_json_parse_value
(
char *pcNewStart,
char *pcRawStart,
VTOY_JSON *pstJson,
const char *pcData,
const char **ppcEnd
);
VTOY_JSON * vtoy_json_create(void);
int vtoy_json_parse(VTOY_JSON *pstJson, const char *szJsonData);
int vtoy_json_scan_parse
(
const VTOY_JSON *pstJson,
UINT32 uiParseNum,
JSON_PARSE *pstJsonParse
);
int vtoy_json_scan_array
(
VTOY_JSON *pstJson,
const char *szKey,
VTOY_JSON **ppstArrayItem
);
int vtoy_json_scan_array_ex
(
VTOY_JSON *pstJson,
const char *szKey,
VTOY_JSON **ppstArrayItem
);
int vtoy_json_scan_object
(
VTOY_JSON *pstJson,
const char *szKey,
VTOY_JSON **ppstObjectItem
);
int vtoy_json_get_int
(
VTOY_JSON *pstJson,
const char *szKey,
int *piValue
);
int vtoy_json_get_uint
(
VTOY_JSON *pstJson,
const char *szKey,
UINT32 *puiValue
);
int vtoy_json_get_uint64
(
VTOY_JSON *pstJson,
const char *szKey,
UINT64 *pui64Value
);
int vtoy_json_get_bool
(
VTOY_JSON *pstJson,
const char *szKey,
UINT8 *pbValue
);
int vtoy_json_get_string
(
VTOY_JSON *pstJson,
const char *szKey,
UINT32 uiBufLen,
char *pcBuf
);
const char * vtoy_json_get_string_ex(VTOY_JSON *pstJson, const char *szKey);
int vtoy_json_destroy(VTOY_JSON *pstJson);
#endif /* __VENTOY_JSON_H__ */
| 3,722 |
C
|
.h
| 147 | 20.877551 | 80 | 0.637955 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,066 |
Language.h
|
ventoy_Ventoy/Ventoy2Disk/Ventoy2Disk/Language.h
|
/******************************************************************************
* Language.h
*
* Copyright (c) 2020, longpanda <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef __LANGUAGE_H__
#define __LANGUAGE_H__
typedef enum STR_ID
{
STR_ERROR = 0,
STR_WARNING, // 1
STR_INFO, // 2
STR_INCORRECT_DIR, //3
STR_INCORRECT_TREE_DIR, //4
STR_DEVICE, //5
STR_LOCAL_VER, //6
STR_DISK_VER, //7
STR_STATUS, //8
STR_INSTALL, //9
STR_UPDATE, //10
STR_UPDATE_TIP, //11
STR_INSTALL_TIP, //12
STR_INSTALL_TIP2,//13
STR_INSTALL_SUCCESS,//14
STR_INSTALL_FAILED,//15
STR_UPDATE_SUCCESS,//16
STR_UPDATE_FAILED,//17
STR_WAIT_PROCESS,//18
STR_MENU_OPTION,//19
STR_MENU_SECURE_BOOT,//20
STR_MENU_PART_CFG,//21
STR_BTN_OK,//22
STR_BTN_CANCEL,//23
STR_PRESERVE_SPACE,//24
STR_SPACE_VAL_INVALID,//25
STR_MENU_CLEAR, //26
STR_CLEAR_SUCCESS, //27
STR_CLEAR_FAILED, //28
STR_MENU_PART_STYLE, //29
STR_DISK_2TB_MBR_ERROR,//30
STR_SHOW_ALL_DEV, //31
STR_PART_ALIGN_4KB, //32
STR_WEB_COMMUNICATION_ERR, //33
STR_WEB_REMOTE_ABNORMAL, //34
STR_WEB_REQUEST_TIMEOUT, //35
STR_WEB_SERVICE_UNAVAILABLE, //36
STR_WEB_TOKEN_MISMATCH, //37
STR_WEB_SERVICE_BUSY, //38
STR_MENU_VTSI_CREATE, //39
STR_VTSI_CREATE_TIP, //40
STR_VTSI_CREATE_SUCCESS, //41
STR_VTSI_CREATE_FAILED, //42
STR_MENU_PART_RESIZE,//43
STR_PART_RESIZE_TIP,//44
STR_PART_RESIZE_SUCCESS,//45
STR_PART_RESIZE_FAILED,//46
STR_PART_RESIZE_UNSUPPORTED,//47
STR_INSTALL_YES_TIP1,//48
STR_INSTALL_YES_TIP2,//49
STR_PART_VENTOY_FS, //50
STR_PART_FS, //51
STR_PART_CLUSTER, //52
STR_PART_CLUSTER_DEFAULT, //53
STR_DONATE, //54
STR_4KN_UNSUPPORTED, //55
STR_ID_MAX
}STR_ID;
extern BOOL g_SecureBoot;
#define VTOY_MENU_SECURE_BOOT 0xA000
#define VTOY_MENU_PART_CFG 0xA001
#define VTOY_MENU_CLEAN 0xA002
#define VTOY_MENU_PART_STYLE 0xA003
#define VTOY_MENU_PART_MBR 0xA004
#define VTOY_MENU_PART_GPT 0xA005
#define VTOY_MENU_ALL_DEV 0xA006
#define VTOY_MENU_VTSI 0xA007
#define VTOY_MENU_PART_RESIZE 0xA008
typedef enum OPT_SUBMENU
{
OPT_SUBMENU_SECURE_BOOT = 0,
OPT_SUBMENU_PART_STYLE,
OPT_SUBMENU_PART_CFG,
OPT_SUBMENU_CLEAR,
OPT_SUBMENU_ALL_DEV,
OPT_SUBMENU_VTSI,
OPT_SUBMENU_PART_RESIZE,
OPT_SUBMENU_MAX
}OPT_SUBMENU;
#define VTOY_MENU_LANGUAGE_BEGIN 0xB000
#define VENTOY_LANGUAGE_INI TEXT(".\\ventoy\\languages.ini")
#define VENTOY_LANGUAGE_JSON TEXT(".\\ventoy\\languages.json")
#define VENTOY_LANGUAGE_INI_A ".\\ventoy\\languages.ini"
#define VENTOY_LANGUAGE_JSON_A ".\\ventoy\\languages.json"
#define VENTOY_CFG_INI TEXT(".\\Ventoy2Disk.ini")
#define VENTOY_CFG_INI_A ".\\Ventoy2Disk.ini"
#define VENTOY_MAX_LANGUAGE 200
#define GET_INI_STRING(Section, Key, Buf) GetPrivateProfileString(Section, Key, TEXT("#"), Buf, sizeof(Buf), VENTOY_LANGUAGE_INI)
typedef struct VENTOY_LANGUAGE
{
WCHAR Name[256];
WCHAR FontFamily[128];
int FontSize;
WCHAR StrId[STR_ID_MAX][64];
WCHAR MsgString[STR_ID_MAX][1024];
}VENTOY_LANGUAGE;
extern VENTOY_LANGUAGE *g_cur_lang_data;
const TCHAR * GetString(enum STR_ID ID);
#define _G(a) GetString(a)
#endif
| 4,035 |
C
|
.h
| 123 | 28.772358 | 130 | 0.674406 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,100 |
vlnk.h
|
ventoy_Ventoy/Vlnk/src/vlnk.h
|
#ifndef __VLNK_H__
#define __VLNK_H__
#define VLNK_FILE_LEN 32768
#define VLNK_NAME_MAX 384
#define VENTOY_GUID { 0x77772020, 0x2e77, 0x6576, { 0x6e, 0x74, 0x6f, 0x79, 0x2e, 0x6e, 0x65, 0x74 }}
#pragma pack(1)
typedef struct ventoy_guid
{
uint32_t data1;
uint16_t data2;
uint16_t data3;
uint8_t data4[8];
}ventoy_guid;
typedef struct ventoy_vlnk
{
ventoy_guid guid; // VENTOY_GUID
uint32_t crc32; // crc32
uint32_t disk_signature;
uint64_t part_offset; // in bytes
char filepath[VLNK_NAME_MAX];
uint8_t reserverd[96];
}ventoy_vlnk;
#pragma pack()
uint32_t ventoy_getcrc32c (uint32_t crc, const void *buf, int size);
int ventoy_create_vlnk(uint32_t disksig, uint64_t partoffset, const char *path, ventoy_vlnk *vlnk);
int CheckVlnkData(ventoy_vlnk *vlnk);
int IsSupportedImgSuffix(char *suffix);
#endif
| 880 |
C
|
.h
| 28 | 28.642857 | 101 | 0.700713 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,134 |
ventoy_http.h
|
ventoy_Ventoy/Plugson/src/Web/ventoy_http.h
|
/******************************************************************************
* ventoy_http.h
*
* Copyright (c) 2021, longpanda <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef __VENTOY_HTTP_H__
#define __VENTOY_HTTP_H__
#include <civetweb.h>
#define MAX_LANGUAGE 256
#define L1 " "
#define L2 " "
#define L3 " "
#define L4 " "
typedef enum bios_mode
{
bios_common = 0,
bios_legacy,
bios_uefi,
bios_ia32,
bios_aa64,
bios_mips,
bios_max
}bios_mode;
typedef enum plugin_type
{
plugin_type_control = 0,
plugin_type_theme,
plugin_type_menu_alias,
plugin_type_menu_tip,
plugin_type_menu_class,
plugin_type_auto_install,
plugin_type_persistence,
plugin_type_injection,
plugin_type_conf_replace,
plugin_type_password,
plugin_type_image_list,
plugin_type_auto_memdisk,
plugin_type_dud,
plugin_type_max
}plugin_type;
typedef struct data_control
{
int default_menu_mode;
int treeview_style;
int filter_dot_underscore;
int sort_casesensitive;
int max_search_level;
int vhd_no_warning;
int filter_iso;
int filter_wim;
int filter_efi;
int filter_img;
int filter_vhd;
int filter_vtoy;
int win11_bypass_check;
int win11_bypass_nro;
int menu_timeout;
int secondary_menu_timeout;
int linux_remount;
int secondary_menu;
int password_asterisk;
char default_search_root[MAX_PATH];
char default_image[MAX_PATH];
char default_kbd_layout[32];
char menu_language[32];
}data_control;
#define display_mode_gui 0
#define display_mode_cli 1
#define display_mode_serial 2
#define display_mode_ser_console 3
typedef struct path_node
{
char path[MAX_PATH];
struct path_node *next;
}path_node;
typedef struct data_theme
{
int default_file;
int resolution_fit;
path_node *filelist;
int display_mode;
char gfxmode[32];
char ventoy_left[32];
char ventoy_top[32];
char ventoy_color[32];
char serial_param[256];
path_node *fontslist;
}data_theme;
#define path_type_file 0
#define path_type_dir 1
typedef struct data_alias_node
{
int type;
char path[MAX_PATH];
char alias[256];
struct data_alias_node *next;
}data_alias_node;
typedef struct data_alias
{
data_alias_node *list;
}data_alias;
typedef struct data_tip_node
{
int type;
char path[MAX_PATH];
char tip[256];
struct data_tip_node *next;
}data_tip_node;
typedef struct data_tip
{
char left[32];
char top[32];
char color[32];
data_tip_node *list;
}data_tip;
#define class_type_key 0
#define class_type_dir 1
#define class_type_parent 2
typedef struct data_class_node
{
int type;
char path[MAX_PATH];
char class[256];
struct data_class_node *next;
}data_class_node;
typedef struct data_class
{
data_class_node *list;
}data_class;
typedef struct data_auto_memdisk
{
path_node *list;
}data_auto_memdisk;
typedef struct data_image_list
{
int type;
path_node *list;
}data_image_list;
typedef struct menu_password
{
int type;
char path[MAX_PATH];
char pwd[256];
struct menu_password *next;
}menu_password;
typedef struct data_password
{
char bootpwd[256];
char isopwd[256];
char wimpwd[256];
char vhdpwd[256];
char imgpwd[256];
char efipwd[256];
char vtoypwd[256];
menu_password *list;
}data_password;
typedef struct conf_replace_node
{
int image;
char path[MAX_PATH];
char org[256];
char new[MAX_PATH];
struct conf_replace_node *next;
}conf_replace_node;
typedef struct data_conf_replace
{
conf_replace_node *list;
}data_conf_replace;
typedef struct injection_node
{
int type;
char path[MAX_PATH];
char archive[MAX_PATH];
struct injection_node *next;
}injection_node;
typedef struct data_injection
{
injection_node *list;
}data_injection;
typedef struct dud_node
{
char path[MAX_PATH];
path_node *list;
struct dud_node *next;
}dud_node;
typedef struct data_dud
{
dud_node *list;
}data_dud;
typedef struct auto_install_node
{
int timeouten;
int timeout;
int autoselen;
int autosel;
int type;
char path[MAX_PATH];
path_node *list;
struct auto_install_node *next;
}auto_install_node;
typedef struct data_auto_install
{
auto_install_node *list;
}data_auto_install;
typedef struct persistence_node
{
int timeouten;
int timeout;
int autoselen;
int autosel;
int type;
char path[MAX_PATH];
path_node *list;
struct persistence_node *next;
}persistence_node;
typedef struct data_persistence
{
persistence_node *list;
}data_persistence;
#define ventoy_save_plug(plug) \
{\
for (i = 0; i < bios_max; i++) \
{\
scnprintf(title, sizeof(title), "%s%s", #plug, g_json_title_postfix[i]);\
g_json_exist[plugin_type_##plug][i] = 0;\
if (ventoy_data_cmp_##plug(g_data_##plug + i, g_data_##plug + bios_max))\
{\
g_json_exist[plugin_type_##plug][i] = 1;\
pos += ventoy_data_save_##plug(g_data_##plug + i, title, JSON_SAVE_BUFFER + pos, JSON_BUF_MAX - pos);\
}\
}\
}
#define api_get_func(conn, json, name) \
{\
int i = 0; \
int pos = 0; \
\
(void)json;\
\
VTOY_JSON_FMT_BEGIN(pos, JSON_BUFFER, JSON_BUF_MAX);\
VTOY_JSON_FMT_ARY_BEGIN();\
\
for (i = 0; i <= bios_max; i++)\
{\
__uiCurPos += ventoy_data_json_##name(g_data_##name + i, JSON_BUFFER + __uiCurPos, JSON_BUF_MAX - __uiCurPos);\
VTOY_JSON_FMT_COMA();\
}\
\
VTOY_JSON_FMT_ARY_END();\
VTOY_JSON_FMT_END(pos);\
\
ventoy_json_buffer(conn, JSON_BUFFER, pos);\
}
#define vtoy_list_free(type, list) \
{\
type *__next = NULL;\
type *__node = list;\
while (__node)\
{\
__next = __node->next;\
free(__node);\
__node = __next;\
}\
(list) = NULL;\
}
#define vtoy_list_del(last, node, LIST, field) \
for (last = node = LIST; node; node = node->next) \
{\
if (strcmp(node->field, field) == 0)\
{\
if (node == LIST)\
{\
LIST = LIST->next;\
}\
else\
{\
last->next = node->next;\
}\
free(node);\
break;\
}\
\
last = node;\
}
#define vtoy_list_del_ex(last, node, LIST, field, cb) \
for (last = node = LIST; node; node = node->next) \
{\
if (strcmp(node->field, field) == 0)\
{\
if (node == LIST)\
{\
LIST = LIST->next;\
}\
else\
{\
last->next = node->next;\
}\
cb(node->list);\
free(node);\
break;\
}\
\
last = node;\
}
#define vtoy_list_add(LIST, cur, node) \
if (LIST)\
{\
cur = LIST;\
while (cur && cur->next)\
{\
cur = cur->next;\
}\
cur->next = node;\
}\
else\
{\
LIST = node;\
}
#define ventoy_parse_json(name) \
{\
int __loop;\
int __len = (int)strlen(#name);\
if (strncmp(#name, node->pcName, __len) == 0)\
{\
for (__loop = 0; __loop < bios_max; __loop++)\
{\
if (strcmp(g_json_title_postfix[__loop], node->pcName + __len) == 0)\
{\
vlog("json parse <%s>\n", node->pcName);\
ventoy_parse_##name(node, g_data_##name + __loop);\
break;\
}\
}\
} \
}
#define CONTROL_PARSE_INT_DEF_0(node, val) \
if (node->unData.pcStrVal[0] == '1') val = 1
#define CONTROL_PARSE_INT_DEF_1(node, val) \
if (node->unData.pcStrVal[0] == '0') val = 0
#define VTOY_JSON_INT(key, val) vtoy_json_get_int(json, key, &val)
#define VTOY_JSON_STR(key, buf) vtoy_json_get_string(json, key, sizeof(buf), buf)
#define VTOY_JSON_STR_EX(key) vtoy_json_get_string_ex(json, key)
typedef int (*ventoy_json_callback)(struct mg_connection *conn, VTOY_JSON *json);
typedef struct JSON_CB
{
const char *method;
ventoy_json_callback callback;
}JSON_CB;
int ventoy_http_init(void);
void ventoy_http_exit(void);
int ventoy_http_start(const char *ip, const char *port);
int ventoy_http_stop(void);
int ventoy_data_save_all(void);
int ventoy_data_real_save_all(int apilock);
#endif /* __VENTOY_HTTP_H__ */
| 8,956 |
C
|
.h
| 369 | 20.138211 | 119 | 0.627598 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,136 |
ventoy_disk.h
|
ventoy_Ventoy/Plugson/src/Core/ventoy_disk.h
|
/******************************************************************************
* ventoy_disk.h
*
* Copyright (c) 2021, longpanda <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef __VENTOY_DISK_H__
#define __VENTOY_DISK_H__
#define MAX_DISK 256
typedef struct ventoy_disk
{
char devname[64];
int pathcase;
char cur_fsname[64];
char cur_capacity[64];
char cur_model[256];
char cur_ventoy_ver[64];
int cur_secureboot;
int cur_part_style;
}ventoy_disk;
#if defined(_MSC_VER) || defined(WIN32)
#else
typedef enum
{
VTOY_DEVICE_UNKNOWN = 0,
VTOY_DEVICE_SCSI,
VTOY_DEVICE_USB,
VTOY_DEVICE_IDE,
VTOY_DEVICE_DAC960,
VTOY_DEVICE_CPQARRAY,
VTOY_DEVICE_FILE,
VTOY_DEVICE_ATARAID,
VTOY_DEVICE_I2O,
VTOY_DEVICE_UBD,
VTOY_DEVICE_DASD,
VTOY_DEVICE_VIODASD,
VTOY_DEVICE_SX8,
VTOY_DEVICE_DM,
VTOY_DEVICE_XVD,
VTOY_DEVICE_SDMMC,
VTOY_DEVICE_VIRTBLK,
VTOY_DEVICE_AOE,
VTOY_DEVICE_MD,
VTOY_DEVICE_LOOP,
VTOY_DEVICE_NVME,
VTOY_DEVICE_RAM,
VTOY_DEVICE_PMEM,
VTOY_DEVICE_END
}ventoy_dev_type;
/* from <linux/major.h> */
#define IDE0_MAJOR 3
#define IDE1_MAJOR 22
#define IDE2_MAJOR 33
#define IDE3_MAJOR 34
#define IDE4_MAJOR 56
#define IDE5_MAJOR 57
#define SCSI_CDROM_MAJOR 11
#define SCSI_DISK0_MAJOR 8
#define SCSI_DISK1_MAJOR 65
#define SCSI_DISK2_MAJOR 66
#define SCSI_DISK3_MAJOR 67
#define SCSI_DISK4_MAJOR 68
#define SCSI_DISK5_MAJOR 69
#define SCSI_DISK6_MAJOR 70
#define SCSI_DISK7_MAJOR 71
#define SCSI_DISK8_MAJOR 128
#define SCSI_DISK9_MAJOR 129
#define SCSI_DISK10_MAJOR 130
#define SCSI_DISK11_MAJOR 131
#define SCSI_DISK12_MAJOR 132
#define SCSI_DISK13_MAJOR 133
#define SCSI_DISK14_MAJOR 134
#define SCSI_DISK15_MAJOR 135
#define COMPAQ_SMART2_MAJOR 72
#define COMPAQ_SMART2_MAJOR1 73
#define COMPAQ_SMART2_MAJOR2 74
#define COMPAQ_SMART2_MAJOR3 75
#define COMPAQ_SMART2_MAJOR4 76
#define COMPAQ_SMART2_MAJOR5 77
#define COMPAQ_SMART2_MAJOR6 78
#define COMPAQ_SMART2_MAJOR7 79
#define COMPAQ_SMART_MAJOR 104
#define COMPAQ_SMART_MAJOR1 105
#define COMPAQ_SMART_MAJOR2 106
#define COMPAQ_SMART_MAJOR3 107
#define COMPAQ_SMART_MAJOR4 108
#define COMPAQ_SMART_MAJOR5 109
#define COMPAQ_SMART_MAJOR6 110
#define COMPAQ_SMART_MAJOR7 111
#define DAC960_MAJOR 48
#define ATARAID_MAJOR 114
#define I2O_MAJOR1 80
#define I2O_MAJOR2 81
#define I2O_MAJOR3 82
#define I2O_MAJOR4 83
#define I2O_MAJOR5 84
#define I2O_MAJOR6 85
#define I2O_MAJOR7 86
#define I2O_MAJOR8 87
#define UBD_MAJOR 98
#define DASD_MAJOR 94
#define VIODASD_MAJOR 112
#define AOE_MAJOR 152
#define SX8_MAJOR1 160
#define SX8_MAJOR2 161
#define XVD_MAJOR 202
#define SDMMC_MAJOR 179
#define LOOP_MAJOR 7
#define MD_MAJOR 9
#define BLKEXT_MAJOR 259
#define RAM_MAJOR 1
#define SCSI_BLK_MAJOR(M) ( \
(M) == SCSI_DISK0_MAJOR \
|| (M) == SCSI_CDROM_MAJOR \
|| ((M) >= SCSI_DISK1_MAJOR && (M) <= SCSI_DISK7_MAJOR) \
|| ((M) >= SCSI_DISK8_MAJOR && (M) <= SCSI_DISK15_MAJOR))
#define IDE_BLK_MAJOR(M) \
((M) == IDE0_MAJOR || \
(M) == IDE1_MAJOR || \
(M) == IDE2_MAJOR || \
(M) == IDE3_MAJOR || \
(M) == IDE4_MAJOR || \
(M) == IDE5_MAJOR)
#define SX8_BLK_MAJOR(M) ((M) >= SX8_MAJOR1 && (M) <= SX8_MAJOR2)
#define I2O_BLK_MAJOR(M) ((M) >= I2O_MAJOR1 && (M) <= I2O_MAJOR8)
#define CPQARRAY_BLK_MAJOR(M) \
(((M) >= COMPAQ_SMART2_MAJOR && (M) <= COMPAQ_SMART2_MAJOR7) || \
(COMPAQ_SMART_MAJOR <= (M) && (M) <= COMPAQ_SMART_MAJOR7))
#endif
int ventoy_disk_init(void);
void ventoy_disk_exit(void);
int ventoy_get_disk_info(char **argv);
const ventoy_disk * ventoy_get_disk_list(int *num);
const ventoy_disk * ventoy_get_disk_node(int id);
int CheckRuntimeEnvironment(char Letter, ventoy_disk *disk);
#endif /* __VENTOY_DISK_H__ */
| 5,097 |
C
|
.h
| 149 | 31.369128 | 79 | 0.61232 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,137 |
ventoy_util.h
|
ventoy_Ventoy/Plugson/src/Core/ventoy_util.h
|
/******************************************************************************
* ventoy_util.h
*
* Copyright (c) 2021, longpanda <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef __VENTOY_UTIL_H__
#define __VENTOY_UTIL_H__
#define PLUGSON_TXZ "plugson.tar.xz"
#define check_free(p) if (p) free(p)
#define vtoy_safe_close_fd(fd) \
{\
if ((fd) >= 0) \
{ \
close(fd); \
(fd) = -1; \
}\
}
extern char g_cur_dir[MAX_PATH];
extern char g_ventoy_dir[MAX_PATH];
#if defined(_MSC_VER) || defined(WIN32)
typedef HANDLE pthread_mutex_t;
static __inline int pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
{
(void)unused;
*mutex = CreateMutex(NULL, FALSE, NULL);
return *mutex == NULL ? -1 : 0;
}
static __inline int pthread_mutex_destroy(pthread_mutex_t *mutex)
{
return CloseHandle(*mutex) == 0 ? -1 : 0;
}
static __inline int pthread_mutex_unlock(pthread_mutex_t *mutex)
{
return ReleaseMutex(*mutex) == 0 ? -1 : 0;
}
static __inline int pthread_mutex_lock(pthread_mutex_t *mutex)
{
return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0 ? 0 : -1;
}
int ventoy_path_case(char *path, int slash);
#else
int ventoy_get_sys_file_line(char *buffer, int buflen, const char *fmt, ...);
#define UINT8 uint8_t
#define UINT16 uint16_t
#define UINT32 uint32_t
#define UINT64 uint64_t
static inline int ventoy_path_case(char *path, int slash)
{
(void)path;
(void)slash;
return 0;
}
#endif
#define LANGUAGE_EN 0
#define LANGUAGE_CN 1
typedef struct SYSINFO
{
char buildtime[128];
int syntax_error;
int invalid_config;
int config_save_error;
int language;
int pathcase;
char cur_fsname[64];
char cur_capacity[64];
char cur_model[256];
char cur_ventoy_ver[64];
int cur_secureboot;
int cur_part_style;
char ip[32];
char port[16];
}SYSINFO;
extern SYSINFO g_sysinfo;
#define TMAGIC "ustar"
#define REGTYPE '0'
#define AREGTYPE '\0'
#define LNKTYPE '1'
#define CHRTYPE '3'
#define BLKTYPE '4'
#define DIRTYPE '5'
#define FIFOTYPE '6'
#define CONTTYPE '7'
#pragma pack(1)
typedef struct tag_tar_head
{
char name[100];
char mode[8];
char uid[8];
char gid[8];
char size[12];
char mtime[12];
char chksum[8];
char typeflag;
char linkname[100];
char magic[6];
char version[2];
char uname[32];
char gname[32];
char devmajor[8];
char devminor[8];
char prefix[155];
char padding[12];
}VENTOY_TAR_HEAD;
#pragma pack()
#define VENTOY_UP_ALIGN(N, align) (((N) + ((align) - 1)) / (align) * (align))
#define VENTOY_FILE_MAX 2048
#if defined(_MSC_VER) || defined(WIN32)
#define million_sleep(a) Sleep(a)
#else
#define million_sleep(a) usleep((a) * 1000)
#endif
typedef struct ventoy_file
{
int size;
char path[MAX_PATH];
int pathlen;
void *addr;
}ventoy_file;
int ventoy_is_file_exist(const char *fmt, ...);
int ventoy_is_directory_exist(const char *fmt, ...);
void ventoy_gen_preudo_uuid(void *uuid);
uint64_t ventoy_get_human_readable_gb(uint64_t SizeBytes);
void ventoy_md5(const void *data, uint32_t len, uint8_t *md5);
int ventoy_is_disk_mounted(const char *devpath);
int unxz(unsigned char *in, int in_size,
int (*fill)(void *dest, unsigned int size),
int (*flush)(void *src, unsigned int size),
unsigned char *out, int *in_used,
void (*error)(char *x));
int ventoy_read_file_to_buf(const char *FileName, int ExtLen, void **Bufer, int *BufLen);
int ventoy_write_buf_to_file(const char *FileName, void *Bufer, int BufLen);
const char * ventoy_get_os_language(void);
int ventoy_get_file_size(const char *file);
int ventoy_www_init(void);
void ventoy_www_exit(void);
int ventoy_decompress_tar(char *tarbuf, int buflen, int *tarsize);
ventoy_file * ventoy_tar_find_file(const char *path);
void ventoy_get_json_path(char *path, char *backup);
int ventoy_copy_file(const char *a, const char *b);
typedef int (*ventoy_http_writeback_pf)(void);
int ventoy_start_writeback_thread(ventoy_http_writeback_pf callback);
void ventoy_stop_writeback_thread(void);
void ventoy_set_writeback_event(void);
extern unsigned char *g_unxz_buffer;
extern int g_unxz_len;
void unxz_error(char *x);
int unxz_flush(void *src, unsigned int size);
char * ventoy_base64_encode(const char *data, int input_length, int *output_length);
size_t utf8_to_utf16(const unsigned char * utf8, size_t utf8_len, unsigned short* utf16, size_t utf16_len);
#endif /* __VENTOY_UTIL_H__ */
| 5,108 |
C
|
.h
| 164 | 28.554878 | 107 | 0.701063 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,161 |
vtoyjump.h
|
ventoy_Ventoy/vtoyjump/vtoyjump/vtoyjump.h
|
/******************************************************************************
* vtoyjump.h
*
* Copyright (c) 2020, longpanda <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef __VTOYJUMP_H__
#define __VTOYJUMP_H__
#pragma comment( linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" )
#define SIZE_1MB (1024 * 1024)
#define VENTOY_EFI_PART_SIZE (32 * SIZE_1MB)
#define VENTOY_GUID { 0x77772020, 0x2e77, 0x6576, { 0x6e, 0x74, 0x6f, 0x79, 0x2e, 0x6e, 0x65, 0x74 }}
#pragma pack(1)
typedef struct ventoy_guid
{
UINT32 data1;
UINT16 data2;
UINT16 data3;
UINT8 data4[8];
}ventoy_guid;
typedef struct ventoy_os_param
{
ventoy_guid guid; // VENTOY_GUID
UINT8 chksum; // checksum
UINT8 vtoy_disk_guid[16];
UINT64 vtoy_disk_size; // disk size in bytes
UINT16 vtoy_disk_part_id; // begin with 1
UINT16 vtoy_disk_part_type; // 0:exfat 1:ntfs other: reserved
char vtoy_img_path[384]; // It seems to be enough, utf-8 format
UINT64 vtoy_img_size; // image file size in bytes
/*
* Ventoy will write a copy of ventoy_image_location data into runtime memory
* this is the physically address and length of that memory.
* Address 0 means no such data exist.
* Address will be aligned by 4KB.
*
*/
UINT64 vtoy_img_location_addr;
UINT32 vtoy_img_location_len;
UINT64 vtoy_reserved[4]; // Internal use by ventoy
UINT8 vtoy_disk_signature[4];
UINT8 reserved[27];
}ventoy_os_param;
typedef struct ventoy_windows_data
{
char auto_install_script[384];
char injection_archive[384];
UINT8 windows11_bypass_check;
UINT32 auto_install_len;
UINT8 windows11_bypass_nro;
UINT8 reserved[255 - 5];
/* auto install script file data ... + auto_install_len */
/* ...... */
}ventoy_windows_data;
typedef struct PART_TABLE
{
UINT8 Active; // 0x00 0x80
UINT8 StartHead;
UINT16 StartSector : 6;
UINT16 StartCylinder : 10;
UINT8 FsFlag;
UINT8 EndHead;
UINT16 EndSector : 6;
UINT16 EndCylinder : 10;
UINT32 StartSectorId;
UINT32 SectorCount;
}PART_TABLE;
typedef struct MBR_HEAD
{
UINT8 BootCode[446];
PART_TABLE PartTbl[4];
UINT8 Byte55;
UINT8 ByteAA;
}MBR_HEAD;
typedef struct VTOY_GPT_HDR
{
CHAR Signature[8]; /* EFI PART */
UINT8 Version[4];
UINT32 Length;
UINT32 Crc;
UINT8 Reserved1[4];
UINT64 EfiStartLBA;
UINT64 EfiBackupLBA;
UINT64 PartAreaStartLBA;
UINT64 PartAreaEndLBA;
GUID DiskGuid;
UINT64 PartTblStartLBA;
UINT32 PartTblTotNum;
UINT32 PartTblEntryLen;
UINT32 PartTblCrc;
UINT8 Reserved2[420];
}VTOY_GPT_HDR;
typedef struct VTOY_GPT_PART_TBL
{
GUID PartType;
GUID PartGuid;
UINT64 StartLBA;
UINT64 LastLBA;
UINT64 Attr;
UINT16 Name[36];
}VTOY_GPT_PART_TBL;
typedef struct VTOY_GPT_INFO
{
MBR_HEAD MBR;
VTOY_GPT_HDR Head;
VTOY_GPT_PART_TBL PartTbl[128];
}VTOY_GPT_INFO;
#pragma pack()
typedef struct VarDiskInfo
{
UINT64 Capacity;
int BusType;
BOOL RemovableMedia;
BYTE DeviceType;
CHAR VendorId[128];
CHAR ProductId[128];
CHAR ProductRev[128];
CHAR SerialNumber[128];
}VarDiskInfo;
typedef struct IsoId
{
CHAR SystemId[64];
CHAR VolumeId[64];
CHAR PulisherId[256];
CHAR PreparerId[256];
}IsoId;
#define SAFE_CLOSE_HANDLE(handle) \
{\
if (handle != INVALID_HANDLE_VALUE) \
{\
CloseHandle(handle); \
(handle) = INVALID_HANDLE_VALUE; \
}\
}
#define safe_sprintf(dst, fmt, ...) sprintf_s(dst, sizeof(dst), fmt, __VA_ARGS__)
#define safe_strcpy(dst, src) strcpy_s(dst, sizeof(dst), src)
#define LASTERR GetLastError()
int unxz(unsigned char *in, int in_size,
int(*fill)(void *dest, unsigned int size),
int(*flush)(void *src, unsigned int size),
unsigned char *out, int *in_used,
void(*error)(char *x));
void Log(const char* Fmt, ...);
int SetupMonNroStart(const char* isopath);
BOOL IsFileExist(const char* Fmt, ...);
BOOL IsDirExist(const char* Fmt, ...);
#endif
| 4,737 |
C
|
.h
| 160 | 26.25 | 101 | 0.68832 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,183 |
vtutil.h
|
ventoy_Ventoy/Unix/ventoy_unix_src/DragonFly/vtutil.h
|
#ifndef __UTIL_H__
#define __UTIL_H__
extern int boot_verbose;
//#define vdebug(fmt, ...)
//#define verror
#define vdebug(fmt, ...) if (boot_verbose) { printf(fmt, ##__VA_ARGS__); usleep(500000); }
#define verror printf
#pragma pack(4)
typedef struct ventoy_image_desc
{
uint64_t disk_size;
uint64_t part1_size;
uint8_t disk_uuid[16];
uint8_t disk_signature[4];
uint32_t img_chunk_count;
/* ventoy_img_chunk list */
}ventoy_image_desc;
typedef struct ventoy_img_chunk
{
uint32_t img_start_sector; // sector size: 2KB
uint32_t img_end_sector; // included
uint64_t disk_start_sector; // in disk_sector_size
uint64_t disk_end_sector; // included
}ventoy_img_chunk;
#pragma pack()
#endif
| 740 |
C
|
.h
| 26 | 25.538462 | 90 | 0.686525 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,212 |
ventoy.h
|
ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/include/grub/ventoy.h
|
/******************************************************************************
* ventoy.h
*
* Copyright (c) 2020, longpanda <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef __VENTOY_H__
#define __VENTOY_H__
#define COMPILE_ASSERT(a, expr) extern char __compile_assert##a[(expr) ? 1 : -1]
#define VENTOY_COMPATIBLE_STR "VENTOY COMPATIBLE"
#define VENTOY_COMPATIBLE_STR_LEN 17
#define VENTOY_GUID { 0x77772020, 0x2e77, 0x6576, { 0x6e, 0x74, 0x6f, 0x79, 0x2e, 0x6e, 0x65, 0x74 }}
typedef enum ventoy_fs_type
{
ventoy_fs_exfat = 0, /* 0: exfat */
ventoy_fs_ntfs, /* 1: NTFS */
ventoy_fs_ext, /* 2: ext2/ext3/ext4 */
ventoy_fs_xfs, /* 3: XFS */
ventoy_fs_udf, /* 4: UDF */
ventoy_fs_fat, /* 5: FAT */
ventoy_fs_max
}ventoy_fs_type;
typedef enum ventoy_chain_type
{
ventoy_chain_linux = 0, /* 0: linux */
ventoy_chain_windows, /* 1: windows */
ventoy_chain_wim, /* 2: wim */
ventoy_chain_max
}ventoy_chain_type;
#pragma pack(1)
typedef struct ventoy_guid
{
grub_uint32_t data1;
grub_uint16_t data2;
grub_uint16_t data3;
grub_uint8_t data4[8];
}ventoy_guid;
typedef struct ventoy_image_disk_region
{
grub_uint32_t image_sector_count; /* image sectors contained in this region (in 2048) */
grub_uint32_t image_start_sector; /* image sector start (in 2048) */
grub_uint64_t disk_start_sector; /* disk sector start (in 512) */
}ventoy_image_disk_region;
typedef struct ventoy_image_location
{
ventoy_guid guid;
/* image sector size, 2048/512 */
grub_uint32_t image_sector_size;
/* disk sector size, normally the value is 512 */
grub_uint32_t disk_sector_size;
grub_uint32_t region_count;
/*
* disk region data (region_count)
* If the image file has more than one fragments in disk,
* there will be more than one region data here.
*
*/
ventoy_image_disk_region regions[1];
/* ventoy_image_disk_region regions[2~region_count-1] */
}ventoy_image_location;
typedef struct ventoy_os_param
{
ventoy_guid guid; // VENTOY_GUID
grub_uint8_t chksum; // checksum
grub_uint8_t vtoy_disk_guid[16];
grub_uint64_t vtoy_disk_size; // disk size in bytes
grub_uint16_t vtoy_disk_part_id; // begin with 1
grub_uint16_t vtoy_disk_part_type; // 0:exfat 1:ntfs other: reserved
char vtoy_img_path[384]; // It seems to be enough, utf-8 format
grub_uint64_t vtoy_img_size; // image file size in bytes
/*
* Ventoy will write a copy of ventoy_image_location data into runtime memory
* this is the physically address and length of that memory.
* Address 0 means no such data exist.
* Address will be aligned by 4KB.
*
*/
grub_uint64_t vtoy_img_location_addr;
grub_uint32_t vtoy_img_location_len;
/*
* These 32 bytes are reserved by ventoy.
*
* vtoy_reserved[0]: vtoy_break_level
* vtoy_reserved[1]: vtoy_debug_level
* vtoy_reserved[2]: vtoy_chain_type 0:Linux 1:Windows 2:wimfile
* vtoy_reserved[3]: vtoy_iso_format 0:iso9660 1:udf
* vtoy_reserved[4]: vtoy_windows_cd_prompt
* vtoy_reserved[5]: vtoy_linux_remount
* vtoy_reserved[6]: vtoy_vlnk
* vtoy_reserved[7~10]: vtoy_disk_sig[4] used for vlnk
*
*/
grub_uint8_t vtoy_reserved[32]; // Internal use by ventoy
grub_uint8_t vtoy_disk_signature[4];
grub_uint8_t reserved[27];
}ventoy_os_param;
typedef struct ventoy_windows_data
{
char auto_install_script[384];
char injection_archive[384];
grub_uint8_t windows11_bypass_check;
grub_uint32_t auto_install_len;
grub_uint8_t windows11_bypass_nro;
grub_uint8_t reserved[255 - 5];
/* auto_intall file buf */
/* ...... + auto_install_len */
}ventoy_windows_data;
typedef struct ventoy_secure_data
{
grub_uint8_t magic1[16]; /* VENTOY_GUID */
grub_uint8_t diskuuid[16];
grub_uint8_t Checksum[16];
grub_uint8_t adminSHA256[32];
grub_uint8_t reserved[4000];
grub_uint8_t magic2[16]; /* VENTOY_GUID */
}ventoy_secure_data;
typedef struct ventoy_vlnk
{
ventoy_guid guid; // VENTOY_GUID
grub_uint32_t crc32; // crc32
grub_uint32_t disk_signature;
grub_uint64_t part_offset; // in bytes
char filepath[384];
grub_uint8_t reserved[96];
}ventoy_vlnk;
#pragma pack()
// compile assert check : sizeof(ventoy_os_param) must be 512
COMPILE_ASSERT(1,sizeof(ventoy_os_param) == 512);
COMPILE_ASSERT(2,sizeof(ventoy_secure_data) == 4096);
COMPILE_ASSERT(3,sizeof(ventoy_vlnk) == 512);
#pragma pack(4)
typedef struct ventoy_chain_head
{
ventoy_os_param os_param;
grub_uint32_t disk_drive;
grub_uint32_t drive_map;
grub_uint32_t disk_sector_size;
grub_uint64_t real_img_size_in_bytes;
grub_uint64_t virt_img_size_in_bytes;
grub_uint32_t boot_catalog;
grub_uint8_t boot_catalog_sector[2048];
grub_uint32_t img_chunk_offset;
grub_uint32_t img_chunk_num;
grub_uint32_t override_chunk_offset;
grub_uint32_t override_chunk_num;
grub_uint32_t virt_chunk_offset;
grub_uint32_t virt_chunk_num;
}ventoy_chain_head;
typedef struct ventoy_image_desc
{
grub_uint64_t disk_size;
grub_uint64_t part1_size;
grub_uint8_t disk_uuid[16];
grub_uint8_t disk_signature[4];
grub_uint32_t img_chunk_count;
/* ventoy_img_chunk list */
}ventoy_image_desc;
typedef struct ventoy_img_chunk
{
grub_uint32_t img_start_sector; // sector size: 2KB
grub_uint32_t img_end_sector; // included
grub_uint64_t disk_start_sector; // in disk_sector_size
grub_uint64_t disk_end_sector; // included
}ventoy_img_chunk;
typedef struct ventoy_override_chunk
{
grub_uint64_t img_offset;
grub_uint32_t override_size;
grub_uint8_t override_data[512];
}ventoy_override_chunk;
typedef struct ventoy_virt_chunk
{
grub_uint32_t mem_sector_start;
grub_uint32_t mem_sector_end;
grub_uint32_t mem_sector_offset;
grub_uint32_t remap_sector_start;
grub_uint32_t remap_sector_end;
grub_uint32_t org_sector_start;
}ventoy_virt_chunk;
#define DEFAULT_CHUNK_NUM 1024
typedef struct ventoy_img_chunk_list
{
grub_uint32_t max_chunk;
grub_uint32_t cur_chunk;
ventoy_img_chunk *chunk;
}ventoy_img_chunk_list;
#pragma pack()
#define ventoy_filt_register grub_file_filter_register
#pragma pack(1)
#define VTOY_MAX_CONF_REPLACE 2
#define GRUB_FILE_REPLACE_MAGIC 0x1258BEEF
#define GRUB_IMG_REPLACE_MAGIC 0x1259BEEF
typedef const char * (*grub_env_get_pf)(const char *name);
typedef int (*grub_env_set_pf)(const char *name, const char *val);
typedef int (*grub_env_printf_pf)(const char *fmt, ...);
typedef struct ventoy_grub_param_file_replace
{
grub_uint32_t magic;
char old_file_name[4][256];
grub_uint32_t old_name_cnt;
grub_uint32_t new_file_virtual_id;
}ventoy_grub_param_file_replace;
typedef struct ventoy_grub_param
{
grub_env_get_pf grub_env_get;
grub_env_set_pf grub_env_set;
ventoy_grub_param_file_replace file_replace;
ventoy_grub_param_file_replace img_replace[VTOY_MAX_CONF_REPLACE];
grub_env_printf_pf grub_env_printf;
}ventoy_grub_param;
#pragma pack()
int grub_ext_get_file_chunk(grub_uint64_t part_start, grub_file_t file, ventoy_img_chunk_list *chunk_list);
int grub_fat_get_file_chunk(grub_uint64_t part_start, grub_file_t file, ventoy_img_chunk_list *chunk_list);
void grub_iso9660_set_nojoliet(int nojoliet);
int grub_iso9660_is_joliet(void);
grub_uint64_t grub_iso9660_get_last_read_pos(grub_file_t file);
grub_uint64_t grub_iso9660_get_last_file_dirent_pos(grub_file_t file);
grub_uint64_t grub_udf_get_file_offset(grub_file_t file);
grub_uint64_t grub_udf_get_last_pd_size_offset(void);
grub_uint64_t grub_udf_get_last_file_attr_offset
(
grub_file_t file,
grub_uint32_t *startBlock,
grub_uint64_t *fe_entry_size_offset
);
int ventoy_is_efi_os(void);
void ventoy_memfile_env_set(const char *prefix, const void *buf, unsigned long long len);
#endif /* __VENTOY_H__ */
| 8,848 |
C
|
.h
| 241 | 32.970954 | 107 | 0.686474 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,219 |
memory.h
|
ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/include/grub/mips64/memory.h
|
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2017 Free Software Foundation, Inc.
*
* GRUB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GRUB 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 GRUB. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRUB_MEMORY_CPU_HEADER
#define GRUB_MEMORY_CPU_HEADER 1
#ifndef ASM_FILE
#include <grub/symbol.h>
#include <grub/err.h>
#include <grub/types.h>
#endif
#ifndef ASM_FILE
typedef grub_addr_t grub_phys_addr_t;
static inline grub_phys_addr_t
grub_vtop (void *a)
{
if (-1 == ((grub_int64_t) a >> 32))
return ((grub_phys_addr_t) a) & 0x1fffffffUL;
return ((grub_phys_addr_t) a) & 0xffffffffffffUL;
}
static inline void *
grub_map_memory (grub_phys_addr_t a, grub_size_t size)
{
if ((a + size) < 0x20000000UL)
return (void *) (a | 0xffffffff80000000UL);
// return (void *) (a | 0x9800000000000000UL);
return (void *) ((a&0x8fffffff) | 0xffffffff00000000UL);
}
static inline void
grub_unmap_memory (void *a __attribute__ ((unused)),
grub_size_t size __attribute__ ((unused)))
{
}
#endif
#endif
| 1,561 |
C
|
.h
| 48 | 30.520833 | 72 | 0.718085 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,221 |
time.h
|
ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/include/grub/mips64/time.h
|
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2003,2004,2005,2007,2017 Free Software Foundation, Inc.
*
* GRUB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GRUB 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 GRUB. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef KERNEL_CPU_TIME_HEADER
#define KERNEL_CPU_TIME_HEADER 1
#ifndef GRUB_UTIL
#define GRUB_TICKS_PER_SECOND (grub_arch_cpuclock / 2)
void grub_timer_init (grub_uint32_t cpuclock);
/* Return the real time in ticks. */
grub_uint64_t grub_get_rtc (void);
extern grub_uint32_t grub_arch_cpuclock;
#endif
static inline void
grub_cpu_idle(void)
{
}
#endif
| 1,119 |
C
|
.h
| 31 | 34.322581 | 74 | 0.750926 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,223 |
types.h
|
ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/include/grub/mips64/types.h
|
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2002,2006,2007,2009,2017 Free Software Foundation, Inc.
*
* GRUB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GRUB 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 GRUB. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRUB_TYPES_CPU_HEADER
#define GRUB_TYPES_CPU_HEADER 1
/* The size of void *. */
#define GRUB_TARGET_SIZEOF_VOID_P 8
/* The size of long. */
#define GRUB_TARGET_SIZEOF_LONG 8
#ifdef GRUB_CPU_MIPS64EL
/* mips64EL is little-endian. */
#undef GRUB_TARGET_WORDS_BIGENDIAN
#elif defined (GRUB_CPU_MIPS64)
/* mips64 is big-endian. */
#define GRUB_TARGET_WORDS_BIGENDIAN
#elif !defined (GRUB_SYMBOL_GENERATOR)
#error Neither GRUB_CPU_MIPS64 nor GRUB_CPU_MIPS64EL is defined
#endif
#endif /* ! GRUB_TYPES_CPU_HEADER */
| 1,284 |
C
|
.h
| 33 | 37.272727 | 74 | 0.744783 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,225 |
asm.h
|
ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/include/grub/mips64/asm.h
|
#ifndef GRUB_MIPS64_ASM_HEADER
#define GRUB_MIPS64_ASM_HEADER 1
#define GRUB_ASM_T4 $a4
#define GRUB_ASM_T5 $a5
#define GRUB_ASM_SZREG 8
#define GRUB_ASM_REG_S sd
#define GRUB_ASM_REG_L ld
#endif
| 198 |
C
|
.h
| 8 | 23.5 | 32 | 0.781915 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,242 |
xpress.h
|
ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/grub-core/ventoy/xpress.h
|
#ifndef _XCA_H
#define _XCA_H
/*
* Copyright (C) 2012 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* Xpress Compression Algorithm (MS-XCA) decompression
*
*/
#include "huffman.h"
/** Number of XCA codes */
#define XCA_CODES 512
/** XCA decompressor */
struct xca {
/** Huffman alphabet */
struct huffman_alphabet alphabet;
/** Raw symbols
*
* Must immediately follow the Huffman alphabet.
*/
huffman_raw_symbol_t raw[XCA_CODES];
/** Code lengths */
uint8_t lengths[XCA_CODES];
};
/** XCA symbol Huffman lengths table */
struct xca_huf_len {
/** Lengths of each symbol */
uint8_t nibbles[ XCA_CODES / 2 ];
} __attribute__ (( packed ));
/**
* Extract Huffman-coded length of a raw symbol
*
* @v lengths Huffman lengths table
* @v symbol Raw symbol
* @ret len Huffman-coded length
*/
static inline unsigned int xca_huf_len ( const struct xca_huf_len *lengths,
unsigned int symbol ) {
return ( ( ( lengths->nibbles[ symbol / 2 ] ) >>
( 4 * ( symbol % 2 ) ) ) & 0x0f );
}
/** Get word from source data stream */
#define XCA_GET16( src ) ( { \
const uint16_t *src16 = src; \
src = ( uint8_t * ) src + sizeof ( *src16 ); \
*src16; } )
/** Get byte from source data stream */
#define XCA_GET8( src ) ( { \
const uint8_t *src8 = src; \
src = ( uint8_t * ) src + sizeof ( *src8 ); \
*src8; } )
/** XCA source data stream end marker */
#define XCA_END_MARKER 256
/** XCA block size */
#define XCA_BLOCK_SIZE ( 64 * 1024 )
extern ssize_t xca_decompress ( const void *data, size_t len, void *buf );
#endif /* _XCA_H */
| 2,312 |
C
|
.h
| 74 | 29.256757 | 75 | 0.685843 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
1,243 |
wimboot.h
|
ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/grub-core/ventoy/wimboot.h
|
/******************************************************************************
* wimboot.h
*
* Copyright (c) 2020, longpanda <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef __WIMBOOT_H__
#define __WIMBOOT_H__
#include <grub/types.h>
#include <grub/misc.h>
#include <grub/mm.h>
#include <grub/err.h>
#include <grub/dl.h>
#include <grub/disk.h>
#include <grub/device.h>
#include <grub/term.h>
#include <grub/partition.h>
#include <grub/file.h>
#include <grub/normal.h>
#include <grub/extcmd.h>
#include <grub/datetime.h>
#include <grub/i18n.h>
#include <grub/net.h>
#include <grub/time.h>
#include <grub/crypto.h>
#include <grub/ventoy.h>
#include "ventoy_def.h"
#define size_t grub_size_t
#define ssize_t grub_ssize_t
#define memset grub_memset
#define memcpy grub_memcpy
#define uint8_t grub_uint8_t
#define uint16_t grub_uint16_t
#define uint32_t grub_uint32_t
#define uint64_t grub_uint64_t
#define int32_t grub_int32_t
#define assert(exp)
//#define DBG grub_printf
#define DBG(fmt, ...)
const char * huffman_bin ( unsigned long value, unsigned int bits );
#endif
| 1,724 |
C
|
.h
| 54 | 30.351852 | 79 | 0.712477 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,244 |
lzx.h
|
ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/grub-core/ventoy/lzx.h
|
#ifndef _LZX_H
#define _LZX_H
/*
* Copyright (C) 2014 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* LZX decompression
*
*/
#include "huffman.h"
/** Number of aligned offset codes */
#define LZX_ALIGNOFFSET_CODES 8
/** Aligned offset code length (in bits) */
#define LZX_ALIGNOFFSET_BITS 3
/** Number of pretree codes */
#define LZX_PRETREE_CODES 20
/** Pretree code length (in bits) */
#define LZX_PRETREE_BITS 4
/** Number of literal main codes */
#define LZX_MAIN_LIT_CODES 256
/** Number of position slots */
#define LZX_POSITION_SLOTS 30
/** Number of main codes */
#define LZX_MAIN_CODES ( LZX_MAIN_LIT_CODES + ( 8 * LZX_POSITION_SLOTS ) )
/** Number of length codes */
#define LZX_LENGTH_CODES 249
/** Block type length (in bits) */
#define LZX_BLOCK_TYPE_BITS 3
/** Default block length */
#define LZX_DEFAULT_BLOCK_LEN 32768
/** Number of repeated offsets */
#define LZX_REPEATED_OFFSETS 3
/** Don't ask */
#define LZX_WIM_MAGIC_FILESIZE 12000000
/** Block types */
enum lzx_block_type {
/** Verbatim block */
LZX_BLOCK_VERBATIM = 1,
/** Aligned offset block */
LZX_BLOCK_ALIGNOFFSET = 2,
/** Uncompressed block */
LZX_BLOCK_UNCOMPRESSED = 3,
};
/** An LZX input stream */
struct lzx_input_stream {
/** Data */
const uint8_t *data;
/** Length */
size_t len;
/** Offset within stream */
size_t offset;
};
/** An LZX output stream */
struct lzx_output_stream {
/** Data, or NULL */
uint8_t *data;
/** Offset within stream */
size_t offset;
/** End of current block within stream */
size_t threshold;
};
/** LZX decompressor */
struct lzx {
/** Input stream */
struct lzx_input_stream input;
/** Output stream */
struct lzx_output_stream output;
/** Accumulator */
uint32_t accumulator;
/** Number of bits in accumulator */
unsigned int bits;
/** Block type */
enum lzx_block_type block_type;
/** Repeated offsets */
unsigned int repeated_offset[LZX_REPEATED_OFFSETS];
/** Aligned offset Huffman alphabet */
struct huffman_alphabet alignoffset;
/** Aligned offset raw symbols
*
* Must immediately follow the aligned offset Huffman
* alphabet.
*/
huffman_raw_symbol_t alignoffset_raw[LZX_ALIGNOFFSET_CODES];
/** Aligned offset code lengths */
uint8_t alignoffset_lengths[LZX_ALIGNOFFSET_CODES];
/** Pretree Huffman alphabet */
struct huffman_alphabet pretree;
/** Pretree raw symbols
*
* Must immediately follow the pretree Huffman alphabet.
*/
huffman_raw_symbol_t pretree_raw[LZX_PRETREE_CODES];
/** Preetree code lengths */
uint8_t pretree_lengths[LZX_PRETREE_CODES];
/** Main Huffman alphabet */
struct huffman_alphabet main;
/** Main raw symbols
*
* Must immediately follow the main Huffman alphabet.
*/
huffman_raw_symbol_t main_raw[LZX_MAIN_CODES];
/** Main code lengths */
struct {
/** Literals */
uint8_t literals[LZX_MAIN_LIT_CODES];
/** Remaining symbols */
uint8_t remainder[ LZX_MAIN_CODES - LZX_MAIN_LIT_CODES ];
} __attribute__ (( packed )) main_lengths;
/** Length Huffman alphabet */
struct huffman_alphabet length;
/** Length raw symbols
*
* Must immediately follow the length Huffman alphabet.
*/
huffman_raw_symbol_t length_raw[LZX_LENGTH_CODES];
/** Length code lengths */
uint8_t length_lengths[LZX_LENGTH_CODES];
};
/**
* Calculate number of footer bits for a given position slot
*
* @v position_slot Position slot
* @ret footer_bits Number of footer bits
*/
static inline unsigned int lzx_footer_bits ( unsigned int position_slot ) {
if ( position_slot < 2 ) {
return 0;
} else if ( position_slot < 38 ) {
return ( ( position_slot / 2 ) - 1 );
} else {
return 17;
}
}
extern ssize_t lzx_decompress ( const void *data, size_t len, void *buf );
#endif /* _LZX_H */
| 4,468 |
C
|
.h
| 152 | 27.388158 | 75 | 0.717183 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
1,246 |
huffman.h
|
ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/grub-core/ventoy/huffman.h
|
#ifndef _HUFFMAN_H
#define _HUFFMAN_H
/*
* Copyright (C) 2014 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file
*
* Huffman alphabets
*
*/
/** Maximum length of a Huffman symbol (in bits) */
#define HUFFMAN_BITS 16
/** Raw huffman symbol */
typedef uint16_t huffman_raw_symbol_t;
/** Quick lookup length for a Huffman symbol (in bits)
*
* This is a policy decision.
*/
#define HUFFMAN_QL_BITS 7
/** Quick lookup shift */
#define HUFFMAN_QL_SHIFT ( HUFFMAN_BITS - HUFFMAN_QL_BITS )
/** A Huffman-coded set of symbols of a given length */
struct huffman_symbols {
/** Length of Huffman-coded symbols (in bits) */
uint8_t bits;
/** Shift to normalise symbols of this length to HUFFMAN_BITS bits */
uint8_t shift;
/** Number of Huffman-coded symbols having this length */
uint16_t freq;
/** First symbol of this length (normalised to HUFFMAN_BITS bits)
*
* Stored as a 32-bit value to allow the value
* (1<<HUFFMAN_BITS ) to be used for empty sets of symbols
* longer than the maximum utilised length.
*/
uint32_t start;
/** Raw symbols having this length */
huffman_raw_symbol_t *raw;
};
/** A Huffman-coded alphabet */
struct huffman_alphabet {
/** Huffman-coded symbol set for each length */
struct huffman_symbols huf[HUFFMAN_BITS];
/** Quick lookup table */
uint8_t lookup[ 1 << HUFFMAN_QL_BITS ];
/** Raw symbols
*
* Ordered by Huffman-coded symbol length, then by symbol
* value. This field has a variable length.
*/
huffman_raw_symbol_t raw[0];
};
/**
* Get Huffman symbol length
*
* @v sym Huffman symbol set
* @ret len Length (in bits)
*/
static inline __attribute__ (( always_inline )) unsigned int
huffman_len ( struct huffman_symbols *sym ) {
return sym->bits;
}
/**
* Get Huffman symbol value
*
* @v sym Huffman symbol set
* @v huf Raw input value (normalised to HUFFMAN_BITS bits)
* @ret raw Raw symbol value
*/
static inline __attribute__ (( always_inline )) huffman_raw_symbol_t
huffman_raw ( struct huffman_symbols *sym, unsigned int huf ) {
return sym->raw[ huf >> sym->shift ];
}
extern int huffman_alphabet ( struct huffman_alphabet *alphabet,
uint8_t *lengths, unsigned int count );
extern struct huffman_symbols *
huffman_sym ( struct huffman_alphabet *alphabet, unsigned int huf );
#endif /* _HUFFMAN_H */
| 3,042 |
C
|
.h
| 94 | 30.351064 | 70 | 0.723926 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
1,248 |
vtoytool.h
|
ventoy_Ventoy/VtoyTool/vtoytool.h
|
/******************************************************************************
* vtoytool.h
*
* Copyright (c) 2022, longpanda <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef __VTOYTOOL_H__
#define __VTOYTOOL_H__
#define IS_DIGIT(x) ((x) >= '0' && (x) <= '9')
#ifndef USE_DIET_C
#ifndef __mips__
typedef unsigned long long uint64_t;
#endif
typedef unsigned int uint32_t;
typedef unsigned short uint16_t;
typedef unsigned char uint8_t;
#endif
#define VENTOY_GUID { 0x77772020, 0x2e77, 0x6576, { 0x6e, 0x74, 0x6f, 0x79, 0x2e, 0x6e, 0x65, 0x74 }}
typedef enum ventoy_fs_type
{
ventoy_fs_exfat = 0, /* 0: exfat */
ventoy_fs_ntfs, /* 1: NTFS */
ventoy_fs_ext, /* 2: ext2/ext3/ext4 */
ventoy_fs_xfs, /* 3: XFS */
ventoy_fs_udf, /* 4: UDF */
ventoy_fs_fat, /* 5: FAT */
ventoy_fs_max
}ventoy_fs_type;
#pragma pack(1)
typedef struct ventoy_guid
{
uint32_t data1;
uint16_t data2;
uint16_t data3;
uint8_t data4[8];
}ventoy_guid;
typedef struct ventoy_image_disk_region
{
uint32_t image_sector_count; /* image sectors contained in this region */
uint32_t image_start_sector; /* image sector start */
uint64_t disk_start_sector; /* disk sector start */
}ventoy_image_disk_region;
typedef struct ventoy_image_location
{
ventoy_guid guid;
/* image sector size, currently this value is always 2048 */
uint32_t image_sector_size;
/* disk sector size, normally the value is 512 */
uint32_t disk_sector_size;
uint32_t region_count;
/*
* disk region data
* If the image file has more than one fragments in disk,
* there will be more than one region data here.
* You can calculate the region count by
*/
ventoy_image_disk_region regions[1];
/* ventoy_image_disk_region regions[2~region_count-1] */
}ventoy_image_location;
typedef struct ventoy_os_param
{
ventoy_guid guid; // VENTOY_GUID
uint8_t chksum; // checksum
uint8_t vtoy_disk_guid[16];
uint64_t vtoy_disk_size; // disk size in bytes
uint16_t vtoy_disk_part_id; // begin with 1
uint16_t vtoy_disk_part_type; // 0:exfat 1:ntfs other: reserved
char vtoy_img_path[384]; // It seems to be enough, utf-8 format
uint64_t vtoy_img_size; // image file size in bytes
/*
* Ventoy will write a copy of ventoy_image_location data into runtime memory
* this is the physically address and length of that memory.
* Address 0 means no such data exist.
* Address will be aligned by 4KB.
*
*/
uint64_t vtoy_img_location_addr;
uint32_t vtoy_img_location_len;
uint8_t vtoy_reserved[32]; // Internal use by ventoy
uint8_t vtoy_disk_signature[4];
uint8_t reserved[27];
}ventoy_os_param;
#pragma pack()
int vtoy_find_disk_by_guid(ventoy_os_param *param, char *diskname);
#endif
| 3,608 |
C
|
.h
| 98 | 33.132653 | 101 | 0.655917 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,272 |
ventoy.h
|
ventoy_Ventoy/IPXE/ipxe_mod_code/ipxe-3fe683e/src/include/ventoy.h
|
#ifndef __VENTOY_VDISK_H__
#define __VENTOY_VDISK_H__
FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
//#define VTOY_DEBUG 1
#define grub_uint64_t uint64_t
#define grub_uint32_t uint32_t
#define grub_uint16_t uint16_t
#define grub_uint8_t uint8_t
#define COMPILE_ASSERT(expr) extern char __compile_assert[(expr) ? 1 : -1]
#define VENTOY_GUID { 0x77772020, 0x2e77, 0x6576, { 0x6e, 0x74, 0x6f, 0x79, 0x2e, 0x6e, 0x65, 0x74 }}
typedef enum ventoy_chain_type
{
ventoy_chain_linux = 0, /* 0: linux */
ventoy_chain_windows, /* 1: windows */
ventoy_chain_wim, /* 2: wim */
ventoy_chain_max
}ventoy_chain_type;
#pragma pack(1)
typedef struct ventoy_guid
{
grub_uint32_t data1;
grub_uint16_t data2;
grub_uint16_t data3;
grub_uint8_t data4[8];
}ventoy_guid;
typedef struct ventoy_image_disk_region
{
grub_uint32_t image_sector_count; /* image sectors contained in this region */
grub_uint32_t image_start_sector; /* image sector start */
grub_uint64_t disk_start_sector; /* disk sector start */
}ventoy_image_disk_region;
typedef struct ventoy_image_location
{
ventoy_guid guid;
/* image sector size, 2048/512 */
grub_uint32_t image_sector_size;
/* disk sector size, normally the value is 512 */
grub_uint32_t disk_sector_size;
grub_uint32_t region_count;
/*
* disk region data
* If the image file has more than one fragments in disk,
* there will be more than one region data here.
*
*/
ventoy_image_disk_region regions[1];
/* ventoy_image_disk_region regions[2~region_count-1] */
}ventoy_image_location;
typedef struct ventoy_os_param
{
ventoy_guid guid; // VENTOY_GUID
grub_uint8_t chksum; // checksum
grub_uint8_t vtoy_disk_guid[16];
grub_uint64_t vtoy_disk_size; // disk size in bytes
grub_uint16_t vtoy_disk_part_id; // begin with 1
grub_uint16_t vtoy_disk_part_type; // 0:exfat 1:ntfs other: reserved
char vtoy_img_path[384]; // It seems to be enough, utf-8 format
grub_uint64_t vtoy_img_size; // image file size in bytes
/*
* Ventoy will write a copy of ventoy_image_location data into runtime memory
* this is the physically address and length of that memory.
* Address 0 means no such data exist.
* Address will be aligned by 4KB.
*
*/
grub_uint64_t vtoy_img_location_addr;
grub_uint32_t vtoy_img_location_len;
grub_uint8_t vtoy_reserved[32]; // Internal use by ventoy
grub_uint8_t vtoy_disk_signature[4];
grub_uint8_t reserved[27];
}ventoy_os_param;
typedef struct ventoy_iso9660_override
{
uint32_t first_sector;
uint32_t first_sector_be;
uint32_t size;
uint32_t size_be;
}ventoy_iso9660_override;
#pragma pack()
// compile assert to check that size of ventoy_os_param must be 512
COMPILE_ASSERT(sizeof(ventoy_os_param) == 512);
#pragma pack(4)
typedef struct ventoy_chain_head
{
ventoy_os_param os_param;
grub_uint32_t disk_drive;
grub_uint32_t drive_map;
grub_uint32_t disk_sector_size;
grub_uint64_t real_img_size_in_bytes;
grub_uint64_t virt_img_size_in_bytes;
grub_uint32_t boot_catalog;
grub_uint8_t boot_catalog_sector[2048];
grub_uint32_t img_chunk_offset;
grub_uint32_t img_chunk_num;
grub_uint32_t override_chunk_offset;
grub_uint32_t override_chunk_num;
grub_uint32_t virt_chunk_offset;
grub_uint32_t virt_chunk_num;
}ventoy_chain_head;
typedef struct ventoy_img_chunk
{
grub_uint32_t img_start_sector; //2KB
grub_uint32_t img_end_sector;
grub_uint64_t disk_start_sector; // in disk_sector_size
grub_uint64_t disk_end_sector;
}ventoy_img_chunk;
typedef struct ventoy_override_chunk
{
grub_uint64_t img_offset;
grub_uint32_t override_size;
grub_uint8_t override_data[512];
}ventoy_override_chunk;
typedef struct ventoy_virt_chunk
{
grub_uint32_t mem_sector_start;
grub_uint32_t mem_sector_end;
grub_uint32_t mem_sector_offset;
grub_uint32_t remap_sector_start;
grub_uint32_t remap_sector_end;
grub_uint32_t org_sector_start;
}ventoy_virt_chunk;
#pragma pack()
#define ventoy_debug_pause() \
{\
printf("\nPress Ctrl+C to continue......");\
sleep(3600);\
printf("\n");\
}
typedef struct ventoy_sector_flag
{
uint8_t flag; // 0:init 1:mem 2:remap
uint64_t remap_lba;
}ventoy_sector_flag;
#define VENTOY_BIOS_FAKE_DRIVE 0xFE
#define VENTOY_BOOT_FIXBIN_DRIVE 0xFD
extern int g_debug;
extern int g_hddmode;
extern int g_bios_disk80;
extern char *g_cmdline_copy;
extern void *g_initrd_addr;
extern size_t g_initrd_len;
extern uint32_t g_disk_sector_size;
unsigned int ventoy_int13_hook (ventoy_chain_head *chain);
int ventoy_int13_boot ( unsigned int drive, void *imginfo, const char *cmdline);
void * ventoy_get_runtime_addr(void);
int ventoy_boot_vdisk(void *data);
uint32_t CalculateCrc32
(
const void *Buffer,
uint32_t Length,
uint32_t InitValue
);
struct smbios3_entry {
uint8_t signature[5];
/** Checksum */
uint8_t checksum;
/** Length */
uint8_t len;
/** Major version */
uint8_t major;
/** Minor version */
uint8_t minor;
uint8_t docrev;
uint8_t revision;
uint8_t reserved;
uint32_t maxsize;
uint64_t address;
} __attribute__ (( packed ));
typedef struct isolinux_boot_info
{
uint32_t isolinux0;
uint32_t isolinux1;
uint32_t PvdLocation;
uint32_t BootFileLocation;
uint32_t BootFileLen;
uint32_t BootFileChecksum;
uint8_t Reserved[40];
}isolinux_boot_info;
//#undef DBGLVL
//#define DBGLVL 7
#endif /* __VENTOY_VDISK_H__ */
| 5,800 |
C
|
.h
| 181 | 28.21547 | 101 | 0.689718 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,274 |
ventoy_int13.h
|
ventoy_Ventoy/IPXE/ipxe_mod_code/ipxe-3fe683e/src/arch/x86/interface/pcbios/ventoy_int13.h
|
#ifndef __VENTOY_INT13_H__
#define __VENTOY_INT13_H__
#undef for_each_sandev
#define for_each_sandev( sandev ) sandev = g_sandev; if (sandev)
int ventoy_vdisk_read(struct san_device*sandev, uint64_t lba, unsigned int count, unsigned long buffer);
static inline int ventoy_sandev_write ( struct san_device *sandev, uint64_t lba, unsigned int count, unsigned long buffer )
{
(void)sandev;
(void)lba;
(void)count;
(void)buffer;
DBGC(sandev, "ventoy_sandev_write\n");
return 0;
}
static inline int ventoy_sandev_reset (void *sandev)
{
(void)sandev;
DBGC(sandev, "ventoy_sandev_reset\n");
return 0;
}
#define sandev_reset ventoy_sandev_reset
#define sandev_read ventoy_vdisk_read
#define sandev_write ventoy_sandev_write
#undef ECANCELED
#define ECANCELED 0x0b
#undef ENODEV
#define ENODEV 0x2c
#undef ENOTSUP
#define ENOTSUP 0x3c
#undef ENOMEM
#define ENOMEM 0x31
#undef EIO
#define EIO 0x1d
#undef ENOEXEC
#define ENOEXEC 0x2e
#undef ENOSPC
#define ENOSPC 0x34
#endif /* __VENTOY_INT13_H__ */
| 1,047 |
C
|
.h
| 38 | 25.342105 | 123 | 0.747748 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,308 |
ventoy_gtk.h
|
ventoy_Ventoy/LinuxGUI/Ventoy2Disk/GTK/ventoy_gtk.h
|
/******************************************************************************
* ventoy_gtk.h
*
* Copyright (c) 2021, longpanda <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef __VENTOY_GTK_H__
#define __VENTOY_GTK_H__
int ventoy_disk_init(void);
void ventoy_disk_exit(void);
int ventoy_http_init(void);
void ventoy_http_exit(void);
int ventoy_log_init(void);
void ventoy_log_exit(void);
void *get_refresh_icon_raw_data(int *len);
void *get_secure_icon_raw_data(int *len);
void *get_window_icon_raw_data(int *len);
int ventoy_func_handler(const char *jsonstr, char *jsonbuf, int buflen);
const char * ventoy_code_get_cur_language(void);
int ventoy_code_get_cur_part_style(void);
void ventoy_code_set_cur_part_style(int style);
int ventoy_code_get_cur_show_all(void);
void ventoy_code_set_cur_show_all(int show_all);
void ventoy_code_set_cur_language(const char *lang);
void ventoy_code_save_cfg(void);
void on_init_window(GtkBuilder *pBuilder);
int on_exit_window(GtkWidget *widget, gpointer data) ;
void ventoy_code_refresh_device(void);
int ventoy_code_is_busy(void);
int ventoy_code_get_percent(void);
int ventoy_code_get_result(void);
int msgbox(GtkMessageType type, GtkButtonsType buttons, const char *strid);
#define VTOY_VER_FMT "<span weight='bold' foreground='red' size='xx-large'>%s</span>"
#define LANG_LABEL_TEXT(id, str) \
gtk_label_set_text(BUILDER_ITEM(GtkLabel, id), vtoy_json_get_string_ex(node->pstChild, str))
#define LANG_BUTTON_TEXT(id, str) \
gtk_button_set_label(BUILDER_ITEM(GtkButton, id), vtoy_json_get_string_ex(node->pstChild, str))
#define LANG_MENU_ITEM_TEXT(id, str) \
gtk_menu_item_set_label(BUILDER_ITEM(GtkMenuItem, id), vtoy_json_get_string_ex(node->pstChild, str))
#define LANG_CHKBTN_TEXT(id, str) \
gtk_check_button_set_label(BUILDER_ITEM(GtkCheckButton, id), vtoy_json_get_string_ex(node->pstChild, str))
#define BUILDER_ITEM(type, id) (type *)gtk_builder_get_object(g_pXmlBuilder, id)
#define SIGNAL(id, act, func) \
g_signal_connect(gtk_builder_get_object(g_pXmlBuilder, id), act, G_CALLBACK(func), NULL)
#define GTK_MSG_ITERATION() while (gtk_events_pending ()) gtk_main_iteration()
#endif /* __VENTOY_GTK_H__ */
| 2,834 |
C
|
.h
| 59 | 46.033898 | 110 | 0.728229 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,309 |
ventoy_http.h
|
ventoy_Ventoy/LinuxGUI/Ventoy2Disk/Web/ventoy_http.h
|
/******************************************************************************
* ventoy_http.h
*
* Copyright (c) 2021, longpanda <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef __VENTOY_HTTP_H__
#define __VENTOY_HTTP_H__
#include <civetweb.h>
typedef enum PROGRESS_POINT
{
PT_START = 1,
PT_PRAPARE_FOR_CLEAN,
PT_DEL_ALL_PART,
PT_LOAD_CORE_IMG,
PT_LOAD_DISK_IMG,
PT_UNXZ_DISK_IMG_FINISH = PT_LOAD_DISK_IMG + 32,
PT_FORMAT_PART1, //10
PT_FORMAT_PART2,
PT_WRITE_VENTOY_START,
PT_WRITE_VENTOY_FINISH = PT_WRITE_VENTOY_START + 8,
PT_WRITE_STG1_IMG,//45
PT_SYNC_DATA1,
PT_CHECK_PART2,
PT_CHECK_PART2_FINISH = PT_CHECK_PART2 + 8,
PT_WRITE_PART_TABLE,//52
PT_SYNC_DATA2,
PT_FINISH
}PROGRESS_POINT;
typedef int (*ventoy_json_callback)(struct mg_connection *conn, VTOY_JSON *json);
typedef struct JSON_CB
{
const char *method;
ventoy_json_callback callback;
}JSON_CB;
typedef struct ventoy_thread_data
{
int diskfd;
uint32_t align4kb;
uint32_t partstyle;
uint32_t secure_boot;
uint64_t reserveBytes;
ventoy_disk *disk;
}ventoy_thread_data;
extern int g_vtoy_exfat_disk_fd;
extern uint64_t g_vtoy_exfat_part_size;
int ventoy_http_init(void);
void ventoy_http_exit(void);
int ventoy_http_start(const char *ip, const char *port);
int ventoy_http_stop(void);
int mkexfat_main(const char *devpath, int fd, uint64_t part_sector_count);
#endif /* __VENTOY_HTTP_H__ */
| 2,120 |
C
|
.h
| 65 | 29.323077 | 81 | 0.694472 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,314 |
ventoy_qt.h
|
ventoy_Ventoy/LinuxGUI/Ventoy2Disk/QT/ventoy_qt.h
|
/******************************************************************************
* ventoy_qt.h
*
* Copyright (c) 2021, longpanda <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef __VENTOY_QT_H__
#define __VENTOY_QT_H__
int ventoy_disk_init(void);
void ventoy_disk_exit(void);
int ventoy_http_init(void);
void ventoy_http_exit(void);
int ventoy_log_init(void);
void ventoy_log_exit(void);
void *get_refresh_icon_raw_data(int *len);
void *get_secure_icon_raw_data(int *len);
void *get_window_icon_raw_data(int *len);
int ventoy_func_handler(const char *jsonstr, char *jsonbuf, int buflen);
const char * ventoy_code_get_cur_language(void);
int ventoy_code_get_cur_part_style(void);
void ventoy_code_set_cur_part_style(int style);
int ventoy_code_get_cur_show_all(void);
void ventoy_code_set_cur_show_all(int show_all);
void ventoy_code_set_cur_language(const char *lang);
void ventoy_code_save_cfg(void);
void ventoy_code_refresh_device(void);
int ventoy_code_is_busy(void);
int ventoy_code_get_percent(void);
int ventoy_code_get_result(void);
#endif /* __VENTOY_QT_H__ */
| 1,710 |
C
|
.h
| 43 | 38.209302 | 79 | 0.719182 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,318 |
ventoy_disk.h
|
ventoy_Ventoy/LinuxGUI/Ventoy2Disk/Core/ventoy_disk.h
|
/******************************************************************************
* ventoy_disk.h
*
* Copyright (c) 2021, longpanda <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef __VENTOY_DISK_H__
#define __VENTOY_DISK_H__
typedef enum
{
VTOY_DEVICE_UNKNOWN = 0,
VTOY_DEVICE_SCSI,
VTOY_DEVICE_USB,
VTOY_DEVICE_IDE,
VTOY_DEVICE_DAC960,
VTOY_DEVICE_CPQARRAY,
VTOY_DEVICE_FILE,
VTOY_DEVICE_ATARAID,
VTOY_DEVICE_I2O,
VTOY_DEVICE_UBD,
VTOY_DEVICE_DASD,
VTOY_DEVICE_VIODASD,
VTOY_DEVICE_SX8,
VTOY_DEVICE_DM,
VTOY_DEVICE_XVD,
VTOY_DEVICE_SDMMC,
VTOY_DEVICE_VIRTBLK,
VTOY_DEVICE_AOE,
VTOY_DEVICE_MD,
VTOY_DEVICE_LOOP,
VTOY_DEVICE_NVME,
VTOY_DEVICE_RAM,
VTOY_DEVICE_PMEM,
VTOY_DEVICE_END
}ventoy_dev_type;
/* from <linux/major.h> */
#define IDE0_MAJOR 3
#define IDE1_MAJOR 22
#define IDE2_MAJOR 33
#define IDE3_MAJOR 34
#define IDE4_MAJOR 56
#define IDE5_MAJOR 57
#define SCSI_CDROM_MAJOR 11
#define SCSI_DISK0_MAJOR 8
#define SCSI_DISK1_MAJOR 65
#define SCSI_DISK2_MAJOR 66
#define SCSI_DISK3_MAJOR 67
#define SCSI_DISK4_MAJOR 68
#define SCSI_DISK5_MAJOR 69
#define SCSI_DISK6_MAJOR 70
#define SCSI_DISK7_MAJOR 71
#define SCSI_DISK8_MAJOR 128
#define SCSI_DISK9_MAJOR 129
#define SCSI_DISK10_MAJOR 130
#define SCSI_DISK11_MAJOR 131
#define SCSI_DISK12_MAJOR 132
#define SCSI_DISK13_MAJOR 133
#define SCSI_DISK14_MAJOR 134
#define SCSI_DISK15_MAJOR 135
#define COMPAQ_SMART2_MAJOR 72
#define COMPAQ_SMART2_MAJOR1 73
#define COMPAQ_SMART2_MAJOR2 74
#define COMPAQ_SMART2_MAJOR3 75
#define COMPAQ_SMART2_MAJOR4 76
#define COMPAQ_SMART2_MAJOR5 77
#define COMPAQ_SMART2_MAJOR6 78
#define COMPAQ_SMART2_MAJOR7 79
#define COMPAQ_SMART_MAJOR 104
#define COMPAQ_SMART_MAJOR1 105
#define COMPAQ_SMART_MAJOR2 106
#define COMPAQ_SMART_MAJOR3 107
#define COMPAQ_SMART_MAJOR4 108
#define COMPAQ_SMART_MAJOR5 109
#define COMPAQ_SMART_MAJOR6 110
#define COMPAQ_SMART_MAJOR7 111
#define DAC960_MAJOR 48
#define ATARAID_MAJOR 114
#define I2O_MAJOR1 80
#define I2O_MAJOR2 81
#define I2O_MAJOR3 82
#define I2O_MAJOR4 83
#define I2O_MAJOR5 84
#define I2O_MAJOR6 85
#define I2O_MAJOR7 86
#define I2O_MAJOR8 87
#define UBD_MAJOR 98
#define DASD_MAJOR 94
#define VIODASD_MAJOR 112
#define AOE_MAJOR 152
#define SX8_MAJOR1 160
#define SX8_MAJOR2 161
#define XVD_MAJOR 202
#define SDMMC_MAJOR 179
#define LOOP_MAJOR 7
#define MD_MAJOR 9
#define BLKEXT_MAJOR 259
#define RAM_MAJOR 1
#define SCSI_BLK_MAJOR(M) ( \
(M) == SCSI_DISK0_MAJOR \
|| (M) == SCSI_CDROM_MAJOR \
|| ((M) >= SCSI_DISK1_MAJOR && (M) <= SCSI_DISK7_MAJOR) \
|| ((M) >= SCSI_DISK8_MAJOR && (M) <= SCSI_DISK15_MAJOR))
#define IDE_BLK_MAJOR(M) \
((M) == IDE0_MAJOR || \
(M) == IDE1_MAJOR || \
(M) == IDE2_MAJOR || \
(M) == IDE3_MAJOR || \
(M) == IDE4_MAJOR || \
(M) == IDE5_MAJOR)
#define SX8_BLK_MAJOR(M) ((M) >= SX8_MAJOR1 && (M) <= SX8_MAJOR2)
#define I2O_BLK_MAJOR(M) ((M) >= I2O_MAJOR1 && (M) <= I2O_MAJOR8)
#define CPQARRAY_BLK_MAJOR(M) \
(((M) >= COMPAQ_SMART2_MAJOR && (M) <= COMPAQ_SMART2_MAJOR7) || \
(COMPAQ_SMART_MAJOR <= (M) && (M) <= COMPAQ_SMART_MAJOR7))
#define VENTOY_FILE_STG1_IMG "boot/core.img.xz"
#define VENTOY_FILE_DISK_IMG "ventoy/ventoy.disk.img.xz"
extern int g_disk_num;
extern ventoy_disk *g_disk_list;
int ventoy_disk_enumerate_all(void);
int ventoy_disk_init(void);
void ventoy_disk_exit(void);
#endif /* __VENTOY_DISK_H__ */
| 4,773 |
C
|
.h
| 135 | 32.674074 | 79 | 0.606618 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,319 |
ventoy_util.h
|
ventoy_Ventoy/LinuxGUI/Ventoy2Disk/Core/ventoy_util.h
|
/******************************************************************************
* ventoy_util.h
*
* Copyright (c) 2021, longpanda <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef __VENTOY_UTIL_H__
#define __VENTOY_UTIL_H__
extern char g_log_file[PATH_MAX];
extern char g_ini_file[PATH_MAX];
#define check_free(p) if (p) free(p)
#define vtoy_safe_close_fd(fd) \
{\
if ((fd) >= 0) \
{ \
close(fd); \
(fd) = -1; \
}\
}
extern uint8_t g_mbr_template[512];
void ventoy_gen_preudo_uuid(void *uuid);
int ventoy_get_disk_part_name(const char *dev, int part, char *partbuf, int bufsize);
int ventoy_get_sys_file_line(char *buffer, int buflen, const char *fmt, ...);
uint64_t ventoy_get_human_readable_gb(uint64_t SizeBytes);
void ventoy_md5(const void *data, uint32_t len, uint8_t *md5);
int ventoy_is_disk_mounted(const char *devpath);
int ventoy_try_umount_disk(const char *devpath);
int unxz(unsigned char *in, int in_size,
int (*fill)(void *dest, unsigned int size),
int (*flush)(void *src, unsigned int size),
unsigned char *out, int *in_used,
void (*error)(char *x));
int ventoy_read_file_to_buf(const char *FileName, int ExtLen, void **Bufer, int *BufLen);
const char * ventoy_get_local_version(void);
int ventoy_fill_gpt(uint64_t size, uint64_t reserve, int align4k, VTOY_GPT_INFO *gpt);
int ventoy_fill_mbr(uint64_t size, uint64_t reserve, int align4k, MBR_HEAD *pMBR);
int VentoyGetLocalBootImg(MBR_HEAD *pMBR);
int ventoy_fill_mbr_4k(uint64_t size, uint64_t reserve, int align4k, MBR_HEAD *pMBR);
#endif /* __VENTOY_UTIL_H__ */
| 2,210 |
C
|
.h
| 52 | 40.326923 | 89 | 0.693915 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,358 |
Ventoy2Disk.h
|
ventoy_Ventoy/LinuxGUI/Ventoy2Disk/Include/Ventoy2Disk.h
|
/******************************************************************************
* Ventoy2Disk.h
*
* Copyright (c) 2021, longpanda <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef __VENTOY2DISK_H__
#define __VENTOY2DISK_H__
#endif /* __VENTOY2DISK_H__ */
| 896 |
C
|
.h
| 22 | 38.636364 | 79 | 0.675862 |
ventoy/Ventoy
| 61,575 | 4,002 | 755 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,991 |
obs-video-gpu-encode.c
|
obsproject_obs-studio/libobs/obs-video-gpu-encode.c
|
/******************************************************************************
Copyright (C) 2023 by Lain Bailey <[email protected]>
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/>.
******************************************************************************/
#include "obs-internal.h"
#define NBSP "\xC2\xA0"
static const char *gpu_encode_frame_name = "gpu_encode_frame";
static void *gpu_encode_thread(void *data)
{
struct obs_core_video_mix *video = data;
uint64_t interval = video_output_get_frame_time(video->video);
DARRAY(obs_encoder_t *) encoders;
int wait_frames = NUM_ENCODE_TEXTURE_FRAMES_TO_WAIT;
da_init(encoders);
os_set_thread_name("obs gpu encode thread");
const char *gpu_encode_thread_name = profile_store_name(
obs_get_profiler_name_store(), "obs_gpu_encode_thread(%g" NBSP "ms)", interval / 1000000.);
profile_register_root(gpu_encode_thread_name, interval);
while (os_sem_wait(video->gpu_encode_semaphore) == 0) {
struct obs_tex_frame tf;
uint64_t timestamp;
uint64_t lock_key;
uint64_t next_key;
size_t lock_count = 0;
uint64_t fer_ts = 0;
if (os_atomic_load_bool(&video->gpu_encode_stop))
break;
if (wait_frames) {
wait_frames--;
continue;
}
profile_start(gpu_encode_thread_name);
os_event_reset(video->gpu_encode_inactive);
/* -------------- */
pthread_mutex_lock(&video->gpu_encoder_mutex);
deque_pop_front(&video->gpu_encoder_queue, &tf, sizeof(tf));
timestamp = tf.timestamp;
lock_key = tf.lock_key;
next_key = tf.lock_key;
video_output_inc_texture_frames(video->video);
for (size_t i = 0; i < video->gpu_encoders.num; i++) {
obs_encoder_t *encoder = obs_encoder_get_ref(video->gpu_encoders.array[i]);
if (encoder)
da_push_back(encoders, &encoder);
}
pthread_mutex_unlock(&video->gpu_encoder_mutex);
/* -------------- */
for (size_t i = 0; i < encoders.num; i++) {
struct encoder_packet pkt = {0};
bool received = false;
bool success = false;
uint32_t skip = 0;
obs_encoder_t *encoder = encoders.array[i];
obs_weak_encoder_t **paired = encoder->paired_encoders.array;
size_t num_paired = encoder->paired_encoders.num;
pkt.timebase_num = encoder->timebase_num * encoder->frame_rate_divisor;
pkt.timebase_den = encoder->timebase_den;
pkt.encoder = encoder;
if (encoder->encoder_group && !encoder->start_ts) {
struct obs_encoder_group *group = encoder->encoder_group;
bool ready = false;
pthread_mutex_lock(&group->mutex);
ready = group->start_timestamp == timestamp;
pthread_mutex_unlock(&group->mutex);
if (!ready)
continue;
}
if (!encoder->first_received && num_paired) {
bool wait_for_audio = false;
for (size_t idx = 0; !wait_for_audio && idx < num_paired; idx++) {
obs_encoder_t *enc = obs_weak_encoder_get_encoder(paired[idx]);
if (!enc)
continue;
if (!enc->first_received || enc->first_raw_ts > timestamp) {
wait_for_audio = true;
}
obs_encoder_release(enc);
}
if (wait_for_audio)
continue;
}
if (video_pause_check(&encoder->pause, timestamp))
continue;
if (encoder->reconfigure_requested) {
encoder->reconfigure_requested = false;
encoder->info.update(encoder->context.data, encoder->context.settings);
}
// an explicit counter is used instead of remainder calculation
// to allow multiple encoders started at the same time to start on
// the same frame
skip = encoder->frame_rate_divisor_counter++;
if (encoder->frame_rate_divisor_counter == encoder->frame_rate_divisor)
encoder->frame_rate_divisor_counter = 0;
if (skip)
continue;
if (!encoder->start_ts)
encoder->start_ts = timestamp;
if (++lock_count == encoders.num)
next_key = 0;
else
next_key++;
/* Get the frame encode request timestamp. This
* needs to be read just before the encode request.
*/
fer_ts = os_gettime_ns();
profile_start(gpu_encode_frame_name);
if (encoder->info.encode_texture2) {
struct encoder_texture tex = {0};
tex.handle = tf.handle;
tex.tex[0] = tf.tex;
tex.tex[1] = tf.tex_uv;
tex.tex[2] = NULL;
success = encoder->info.encode_texture2(encoder->context.data, &tex, encoder->cur_pts,
lock_key, &next_key, &pkt, &received);
} else {
success = encoder->info.encode_texture(encoder->context.data, tf.handle,
encoder->cur_pts, lock_key, &next_key, &pkt,
&received);
}
profile_end(gpu_encode_frame_name);
/* Generate and enqueue the frame timing metrics, namely
* the CTS (composition time), FER (frame encode request), FERC
* (frame encode request complete) and current PTS. PTS is used to
* associate the frame timing data with the encode packet. */
if (tf.timestamp) {
struct encoder_packet_time *ept = da_push_back_new(encoder->encoder_packet_times);
// Get the frame encode request complete timestamp
if (success) {
ept->ferc = os_gettime_ns();
} else {
// Encode had error, set ferc to 0
ept->ferc = 0;
}
ept->pts = encoder->cur_pts;
ept->cts = tf.timestamp;
ept->fer = fer_ts;
}
send_off_encoder_packet(encoder, success, received, &pkt);
lock_key = next_key;
encoder->cur_pts += encoder->timebase_num * encoder->frame_rate_divisor;
}
/* -------------- */
pthread_mutex_lock(&video->gpu_encoder_mutex);
tf.lock_key = next_key;
if (--tf.count) {
tf.timestamp += interval;
deque_push_front(&video->gpu_encoder_queue, &tf, sizeof(tf));
video_output_inc_texture_skipped_frames(video->video);
} else {
deque_push_back(&video->gpu_encoder_avail_queue, &tf, sizeof(tf));
}
pthread_mutex_unlock(&video->gpu_encoder_mutex);
/* -------------- */
os_event_signal(video->gpu_encode_inactive);
for (size_t i = 0; i < encoders.num; i++)
obs_encoder_release(encoders.array[i]);
da_resize(encoders, 0);
profile_end(gpu_encode_thread_name);
profile_reenable_thread();
}
da_free(encoders);
return NULL;
}
bool init_gpu_encoding(struct obs_core_video_mix *video)
{
const struct video_output_info *info = video_output_get_info(video->video);
video->gpu_encode_stop = false;
deque_reserve(&video->gpu_encoder_avail_queue, NUM_ENCODE_TEXTURES);
for (size_t i = 0; i < NUM_ENCODE_TEXTURES; i++) {
gs_texture_t *tex;
gs_texture_t *tex_uv;
if (info->format == VIDEO_FORMAT_P010) {
gs_texture_create_p010(&tex, &tex_uv, info->width, info->height,
GS_RENDER_TARGET | GS_SHARED_KM_TEX);
} else {
gs_texture_create_nv12(&tex, &tex_uv, info->width, info->height,
GS_RENDER_TARGET | GS_SHARED_KM_TEX);
}
if (!tex) {
return false;
}
#ifdef _WIN32
uint32_t handle = gs_texture_get_shared_handle(tex);
#else
uint32_t handle = (uint32_t)-1;
#endif
struct obs_tex_frame frame = {.tex = tex, .tex_uv = tex_uv, .handle = handle};
deque_push_back(&video->gpu_encoder_avail_queue, &frame, sizeof(frame));
}
if (os_sem_init(&video->gpu_encode_semaphore, 0) != 0)
return false;
if (os_event_init(&video->gpu_encode_inactive, OS_EVENT_TYPE_MANUAL) != 0)
return false;
if (pthread_create(&video->gpu_encode_thread, NULL, gpu_encode_thread, video) != 0)
return false;
os_event_signal(video->gpu_encode_inactive);
video->gpu_encode_thread_initialized = true;
return true;
}
void stop_gpu_encoding_thread(struct obs_core_video_mix *video)
{
if (video->gpu_encode_thread_initialized) {
os_atomic_set_bool(&video->gpu_encode_stop, true);
os_sem_post(video->gpu_encode_semaphore);
pthread_join(video->gpu_encode_thread, NULL);
video->gpu_encode_thread_initialized = false;
}
}
void free_gpu_encoding(struct obs_core_video_mix *video)
{
if (video->gpu_encode_semaphore) {
os_sem_destroy(video->gpu_encode_semaphore);
video->gpu_encode_semaphore = NULL;
}
if (video->gpu_encode_inactive) {
os_event_destroy(video->gpu_encode_inactive);
video->gpu_encode_inactive = NULL;
}
#define free_deque(x) \
do { \
while (x.size) { \
struct obs_tex_frame frame; \
deque_pop_front(&x, &frame, sizeof(frame)); \
gs_texture_destroy(frame.tex); \
gs_texture_destroy(frame.tex_uv); \
} \
deque_free(&x); \
} while (false)
free_deque(video->gpu_encoder_queue);
free_deque(video->gpu_encoder_avail_queue);
#undef free_deque
}
| 9,217 |
C
|
.c
| 241 | 34.261411 | 93 | 0.649568 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
1,999 |
obs-nix-platform.c
|
obsproject_obs-studio/libobs/obs-nix-platform.c
|
/******************************************************************************
Copyright (C) 2019 by Jason Francis <[email protected]>
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/>.
******************************************************************************/
#include "obs-nix-platform.h"
#include <assert.h>
static enum obs_nix_platform_type obs_nix_platform = OBS_NIX_PLATFORM_X11_EGL;
static void *obs_nix_platform_display = NULL;
void obs_set_nix_platform(enum obs_nix_platform_type platform)
{
assert(platform != OBS_NIX_PLATFORM_INVALID);
obs_nix_platform = platform;
}
enum obs_nix_platform_type obs_get_nix_platform(void)
{
return obs_nix_platform;
}
void obs_set_nix_platform_display(void *display)
{
obs_nix_platform_display = display;
}
void *obs_get_nix_platform_display(void)
{
return obs_nix_platform_display;
}
| 1,451 |
C
|
.c
| 34 | 39.911765 | 79 | 0.680654 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,007 |
obs-av1.c
|
obsproject_obs-studio/libobs/obs-av1.c
|
// SPDX-FileCopyrightText: 2023 David Rosca <[email protected]>
//
// SPDX-License-Identifier: GPL-2.0-or-later
#include "obs-av1.h"
#include "obs.h"
static inline uint64_t leb128(const uint8_t *buf, size_t size, size_t *len)
{
uint64_t value = 0;
uint8_t leb128_byte;
*len = 0;
for (int i = 0; i < 8; i++) {
if (size-- < 1)
break;
(*len)++;
leb128_byte = buf[i];
value |= (leb128_byte & 0x7f) << (i * 7);
if (!(leb128_byte & 0x80))
break;
}
return value;
}
static inline unsigned int get_bits(uint8_t val, unsigned int n, unsigned int count)
{
return (val >> (8 - n - count)) & ((1 << (count - 1)) * 2 - 1);
}
static void parse_obu_header(const uint8_t *buf, size_t size, size_t *obu_start, size_t *obu_size, int *obu_type)
{
int extension_flag, has_size_field;
size_t size_len = 0;
*obu_start = 0;
*obu_size = 0;
*obu_type = 0;
if (size < 1)
return;
*obu_type = get_bits(*buf, 1, 4);
extension_flag = get_bits(*buf, 5, 1);
has_size_field = get_bits(*buf, 6, 1);
if (extension_flag)
(*obu_start)++;
(*obu_start)++;
if (has_size_field)
*obu_size = (size_t)leb128(buf + *obu_start, size - *obu_start, &size_len);
else
*obu_size = size - 1;
*obu_start += size_len;
}
// Pass a static 10 byte buffer in. The max size for a leb128.
static inline void encode_uleb128(uint64_t val, uint8_t *out_buf, size_t *len_out)
{
size_t num_bytes = 0;
uint8_t b = val & 0x7f;
val >>= 7;
while (val > 0) {
out_buf[num_bytes] = b | 0x80;
++num_bytes;
b = val & 0x7f;
val >>= 7;
}
out_buf[num_bytes] = b;
++num_bytes;
*len_out = num_bytes;
}
/* metadata_obu_itu_t35() is a public symbol. Maintain the function
* and make it call the more general metadata_obu() function.
*/
void metadata_obu_itu_t35(const uint8_t *itut_t35_buffer, size_t itut_bufsize, uint8_t **out_buffer,
size_t *outbuf_size)
{
metadata_obu(itut_t35_buffer, itut_bufsize, out_buffer, outbuf_size, METADATA_TYPE_ITUT_T35);
}
// Create an OBU to carry AV1 metadata types, including captions and user private data
void metadata_obu(const uint8_t *source_buffer, size_t source_bufsize, uint8_t **out_buffer, size_t *outbuf_size,
uint8_t metadata_type)
{
/* From the AV1 spec: 5.3.2 OBU Header Syntax
* -------------
* obu_forbidden_bit (1)
* obu_type (4) // In this case OBS_OBU_METADATA
* obu_extension_flag (1)
* obu_has_size_field (1) // Must be set, size of OBU is variable
* obu_reserved_1bit (1)
* if(obu_extension_flag == 1)
* // skip, because we aren't setting this
*/
uint8_t obu_header_byte = (OBS_OBU_METADATA << 3) | (1 << 1);
/* From the AV1 spec: 5.3.1 General OBU Syntax
* if (obu_has_size_field)
* obu_size leb128()
* else
* obu_size = sz - 1 - obu_extension_flag
*
* // Skipping portions unrelated to this OBU type
*
* if (obu_type == OBU_METADATA)
* metdata_obu()
* 5.8.1 General metadata OBU Syntax
* // leb128(metadatatype) should always be 1 byte +1 for trailing bits
* metadata_type leb128()
* 5.8.2 Metadata ITUT T35 syntax
* if (metadata_type == METADATA_TYPE_ITUT_T35)
* // add ITUT T35 payload
* 5.8.1 General metadata OBU Syntax
* // trailing bits will always be 0x80 because
* // everything in here is byte aligned
* trailing_bits( obu_size * 8 - payloadBits )
*/
int64_t size_field = 1 + source_bufsize + 1;
uint8_t size_buf[10];
size_t size_buf_size = 0;
encode_uleb128(size_field, size_buf, &size_buf_size);
// header + obu_size + metadata_type + metadata_payload + trailing_bits
*outbuf_size = 1 + size_buf_size + 1 + source_bufsize + 1;
*out_buffer = bzalloc(*outbuf_size);
size_t offset = 0;
(*out_buffer)[0] = obu_header_byte;
++offset;
memcpy((*out_buffer) + offset, size_buf, size_buf_size);
offset += size_buf_size;
(*out_buffer)[offset] = metadata_type;
++offset;
memcpy((*out_buffer) + offset, source_buffer, source_bufsize);
offset += source_bufsize;
/* From AV1 spec: 6.2.1 General OBU semantics
* ... Trailing bits are always present, unless the OBU consists of only
* the header. Trailing bits achieve byte alignment when the payload of
* an OBU is not byte aligned. The trailing bits may also used for
* additional byte padding, and if used are taken into account in the
* sz value. In all cases, the pattern used for the trailing bits
* guarantees that all OBUs (except header-only OBUs) end with the same
* pattern: one bit set to one, optionally followed by zeros. */
(*out_buffer)[offset] = 0x80;
}
bool obs_av1_keyframe(const uint8_t *data, size_t size)
{
const uint8_t *start = data, *end = data + size;
while (start < end) {
size_t obu_start, obu_size;
int obu_type;
parse_obu_header(start, end - start, &obu_start, &obu_size, &obu_type);
if (obu_size) {
if (obu_type == OBS_OBU_FRAME || obu_type == OBS_OBU_FRAME_HEADER) {
uint8_t val = *(start + obu_start);
if (!get_bits(val, 0, 1)) // show_existing_frame
return get_bits(val, 1, 2) == 0; // frame_type
return false;
}
}
start += obu_start + obu_size;
}
return false;
}
void obs_extract_av1_headers(const uint8_t *packet, size_t size, uint8_t **new_packet_data, size_t *new_packet_size,
uint8_t **header_data, size_t *header_size)
{
DARRAY(uint8_t) new_packet;
DARRAY(uint8_t) header;
const uint8_t *start = packet, *end = packet + size;
da_init(new_packet);
da_init(header);
while (start < end) {
size_t obu_start, obu_size;
int obu_type;
parse_obu_header(start, end - start, &obu_start, &obu_size, &obu_type);
if (obu_type == OBS_OBU_METADATA || obu_type == OBS_OBU_SEQUENCE_HEADER) {
da_push_back_array(header, start, obu_start + obu_size);
}
da_push_back_array(new_packet, start, obu_start + obu_size);
start += obu_start + obu_size;
}
*new_packet_data = new_packet.array;
*new_packet_size = new_packet.num;
*header_data = header.array;
*header_size = header.num;
}
| 5,972 |
C
|
.c
| 174 | 31.695402 | 116 | 0.66204 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,011 |
obs-avc.c
|
obsproject_obs-studio/libobs/obs-avc.c
|
/******************************************************************************
Copyright (C) 2023 by Lain Bailey <[email protected]>
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/>.
******************************************************************************/
#include "obs-avc.h"
#include "obs.h"
#include "obs-nal.h"
#include "util/array-serializer.h"
#include "util/bitstream.h"
bool obs_avc_keyframe(const uint8_t *data, size_t size)
{
const uint8_t *nal_start, *nal_end;
const uint8_t *end = data + size;
nal_start = obs_nal_find_startcode(data, end);
while (true) {
while (nal_start < end && !*(nal_start++))
;
if (nal_start == end)
break;
const uint8_t type = nal_start[0] & 0x1F;
if (type == OBS_NAL_SLICE_IDR || type == OBS_NAL_SLICE)
return type == OBS_NAL_SLICE_IDR;
nal_end = obs_nal_find_startcode(nal_start, end);
nal_start = nal_end;
}
return false;
}
const uint8_t *obs_avc_find_startcode(const uint8_t *p, const uint8_t *end)
{
return obs_nal_find_startcode(p, end);
}
static int compute_avc_keyframe_priority(const uint8_t *nal_start, bool *is_keyframe, int priority)
{
const int type = nal_start[0] & 0x1F;
if (type == OBS_NAL_SLICE_IDR)
*is_keyframe = true;
const int new_priority = nal_start[0] >> 5;
if (priority < new_priority)
priority = new_priority;
return priority;
}
static void serialize_avc_data(struct serializer *s, const uint8_t *data, size_t size, bool *is_keyframe, int *priority)
{
const uint8_t *const end = data + size;
const uint8_t *nal_start = obs_nal_find_startcode(data, end);
while (true) {
while (nal_start < end && !*(nal_start++))
;
if (nal_start == end)
break;
*priority = compute_avc_keyframe_priority(nal_start, is_keyframe, *priority);
const uint8_t *const nal_end = obs_nal_find_startcode(nal_start, end);
const size_t nal_size = nal_end - nal_start;
s_wb32(s, (uint32_t)nal_size);
s_write(s, nal_start, nal_size);
nal_start = nal_end;
}
}
void obs_parse_avc_packet(struct encoder_packet *avc_packet, const struct encoder_packet *src)
{
struct array_output_data output;
struct serializer s;
long ref = 1;
array_output_serializer_init(&s, &output);
*avc_packet = *src;
serialize(&s, &ref, sizeof(ref));
serialize_avc_data(&s, src->data, src->size, &avc_packet->keyframe, &avc_packet->priority);
avc_packet->data = output.bytes.array + sizeof(ref);
avc_packet->size = output.bytes.num - sizeof(ref);
avc_packet->drop_priority = avc_packet->priority;
}
int obs_parse_avc_packet_priority(const struct encoder_packet *packet)
{
int priority = packet->priority;
const uint8_t *const data = packet->data;
const uint8_t *const end = data + packet->size;
const uint8_t *nal_start = obs_nal_find_startcode(data, end);
while (true) {
while (nal_start < end && !*(nal_start++))
;
if (nal_start == end)
break;
bool unused;
priority = compute_avc_keyframe_priority(nal_start, &unused, priority);
nal_start = obs_nal_find_startcode(nal_start, end);
}
return priority;
}
static inline bool has_start_code(const uint8_t *data)
{
if (data[0] != 0 || data[1] != 0)
return false;
return data[2] == 1 || (data[2] == 0 && data[3] == 1);
}
static void get_sps_pps(const uint8_t *data, size_t size, const uint8_t **sps, size_t *sps_size, const uint8_t **pps,
size_t *pps_size)
{
const uint8_t *nal_start, *nal_end;
const uint8_t *end = data + size;
int type;
nal_start = obs_nal_find_startcode(data, end);
while (true) {
while (nal_start < end && !*(nal_start++))
;
if (nal_start == end)
break;
nal_end = obs_nal_find_startcode(nal_start, end);
type = nal_start[0] & 0x1F;
if (type == OBS_NAL_SPS) {
*sps = nal_start;
*sps_size = nal_end - nal_start;
} else if (type == OBS_NAL_PPS) {
*pps = nal_start;
*pps_size = nal_end - nal_start;
}
nal_start = nal_end;
}
}
static inline uint8_t get_ue_golomb(struct bitstream_reader *gb)
{
int i = 0;
while (i < 32 && !bitstream_reader_read_bits(gb, 1))
i++;
return bitstream_reader_read_bits(gb, i) + (1 << i) - 1;
}
static void get_sps_high_params(const uint8_t *sps, size_t size, uint8_t *chroma_format_idc, uint8_t *bit_depth_luma,
uint8_t *bit_depth_chroma)
{
struct bitstream_reader gb;
/* Extract RBSP */
uint8_t *rbsp = bzalloc(size);
size_t i = 0;
size_t rbsp_size = 0;
while (i + 2 < size) {
if (sps[i] == 0 && sps[i + 1] == 0 && sps[i + 2] == 3) {
rbsp[rbsp_size++] = sps[i++];
rbsp[rbsp_size++] = sps[i++];
// skip emulation_prevention_three_byte
i++;
} else {
rbsp[rbsp_size++] = sps[i++];
}
}
while (i < size)
rbsp[rbsp_size++] = sps[i++];
/* Read relevant information from SPS */
bitstream_reader_init(&gb, rbsp, rbsp_size);
// skip a whole bunch of stuff we don't care about
bitstream_reader_read_bits(&gb, 24); // profile, constraint flags, level
get_ue_golomb(&gb); // id
*chroma_format_idc = get_ue_golomb(&gb);
// skip separate_colour_plane_flag
if (*chroma_format_idc == 3)
bitstream_reader_read_bits(&gb, 1);
*bit_depth_luma = get_ue_golomb(&gb);
*bit_depth_chroma = get_ue_golomb(&gb);
bfree(rbsp);
}
size_t obs_parse_avc_header(uint8_t **header, const uint8_t *data, size_t size)
{
struct array_output_data output;
struct serializer s;
const uint8_t *sps = NULL, *pps = NULL;
size_t sps_size = 0, pps_size = 0;
array_output_serializer_init(&s, &output);
if (size <= 6)
return 0;
if (!has_start_code(data)) {
*header = bmemdup(data, size);
return size;
}
get_sps_pps(data, size, &sps, &sps_size, &pps, &pps_size);
if (!sps || !pps || sps_size < 4)
return 0;
s_w8(&s, 0x01);
s_write(&s, sps + 1, 3);
s_w8(&s, 0xff);
s_w8(&s, 0xe1);
s_wb16(&s, (uint16_t)sps_size);
s_write(&s, sps, sps_size);
s_w8(&s, 0x01);
s_wb16(&s, (uint16_t)pps_size);
s_write(&s, pps, pps_size);
uint8_t profile_idc = sps[1];
/* Additional data required for high, high10, high422, high444 profiles.
* See ISO/IEC 14496-15 Section 5.3.3.1.2. */
if (profile_idc == 100 || profile_idc == 110 || profile_idc == 122 || profile_idc == 244) {
uint8_t chroma_format_idc, bit_depth_luma, bit_depth_chroma;
get_sps_high_params(sps + 1, sps_size - 1, &chroma_format_idc, &bit_depth_luma, &bit_depth_chroma);
// reserved + chroma_format
s_w8(&s, 0xfc | chroma_format_idc);
// reserved + bit_depth_luma_minus8
s_w8(&s, 0xf8 | bit_depth_luma);
// reserved + bit_depth_chroma_minus8
s_w8(&s, 0xf8 | bit_depth_chroma);
// numOfSequenceParameterSetExt
s_w8(&s, 0);
}
*header = output.bytes.array;
return output.bytes.num;
}
void obs_extract_avc_headers(const uint8_t *packet, size_t size, uint8_t **new_packet_data, size_t *new_packet_size,
uint8_t **header_data, size_t *header_size, uint8_t **sei_data, size_t *sei_size)
{
DARRAY(uint8_t) new_packet;
DARRAY(uint8_t) header;
DARRAY(uint8_t) sei;
const uint8_t *nal_start, *nal_end, *nal_codestart;
const uint8_t *end = packet + size;
da_init(new_packet);
da_init(header);
da_init(sei);
nal_start = obs_nal_find_startcode(packet, end);
nal_end = NULL;
while (nal_end != end) {
nal_codestart = nal_start;
while (nal_start < end && !*(nal_start++))
;
if (nal_start == end)
break;
const uint8_t type = nal_start[0] & 0x1F;
nal_end = obs_nal_find_startcode(nal_start, end);
if (!nal_end)
nal_end = end;
if (type == OBS_NAL_SPS || type == OBS_NAL_PPS) {
da_push_back_array(header, nal_codestart, nal_end - nal_codestart);
} else if (type == OBS_NAL_SEI) {
da_push_back_array(sei, nal_codestart, nal_end - nal_codestart);
} else {
da_push_back_array(new_packet, nal_codestart, nal_end - nal_codestart);
}
nal_start = nal_end;
}
*new_packet_data = new_packet.array;
*new_packet_size = new_packet.num;
*header_data = header.array;
*header_size = header.num;
*sei_data = sei.array;
*sei_size = sei.num;
}
| 8,508 |
C
|
.c
| 249 | 31.429719 | 120 | 0.660315 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,021 |
obs-ffmpeg-compat.h
|
obsproject_obs-studio/libobs/obs-ffmpeg-compat.h
|
#pragma once
#include <libavcodec/avcodec.h>
/* LIBAVCODEC_VERSION_CHECK checks for the right version of libav and FFmpeg
* a is the major version
* b and c the minor and micro versions of libav
* d and e the minor and micro versions of FFmpeg */
#define LIBAVCODEC_VERSION_CHECK(a, b, c, d, e) \
((LIBAVCODEC_VERSION_MICRO < 100 && LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(a, b, c)) || \
(LIBAVCODEC_VERSION_MICRO >= 100 && LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(a, d, e)))
#define INPUT_BUFFER_PADDING_SIZE AV_INPUT_BUFFER_PADDING_SIZE
| 599 |
C
|
.c
| 10 | 58 | 99 | 0.670648 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,023 |
obs-view.c
|
obsproject_obs-studio/libobs/obs-view.c
|
/******************************************************************************
Copyright (C) 2023 by Lain Bailey <[email protected]>
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/>.
******************************************************************************/
#include "obs.h"
#include "obs-internal.h"
bool obs_view_init(struct obs_view *view)
{
if (!view)
return false;
pthread_mutex_init_value(&view->channels_mutex);
if (pthread_mutex_init(&view->channels_mutex, NULL) != 0) {
blog(LOG_ERROR, "obs_view_init: Failed to create mutex");
return false;
}
return true;
}
obs_view_t *obs_view_create(void)
{
struct obs_view *view = bzalloc(sizeof(struct obs_view));
if (!obs_view_init(view)) {
bfree(view);
view = NULL;
}
return view;
}
void obs_view_free(struct obs_view *view)
{
if (!view)
return;
for (size_t i = 0; i < MAX_CHANNELS; i++) {
struct obs_source *source = view->channels[i];
if (source) {
obs_source_deactivate(source, AUX_VIEW);
obs_source_release(source);
}
}
memset(view->channels, 0, sizeof(view->channels));
pthread_mutex_destroy(&view->channels_mutex);
}
void obs_view_destroy(obs_view_t *view)
{
if (view) {
obs_view_free(view);
bfree(view);
}
}
obs_source_t *obs_view_get_source(obs_view_t *view, uint32_t channel)
{
obs_source_t *source;
assert(channel < MAX_CHANNELS);
if (!view)
return NULL;
if (channel >= MAX_CHANNELS)
return NULL;
pthread_mutex_lock(&view->channels_mutex);
source = obs_source_get_ref(view->channels[channel]);
pthread_mutex_unlock(&view->channels_mutex);
return source;
}
void obs_view_set_source(obs_view_t *view, uint32_t channel, obs_source_t *source)
{
struct obs_source *prev_source;
assert(channel < MAX_CHANNELS);
if (!view)
return;
if (channel >= MAX_CHANNELS)
return;
pthread_mutex_lock(&view->channels_mutex);
source = obs_source_get_ref(source);
prev_source = view->channels[channel];
view->channels[channel] = source;
pthread_mutex_unlock(&view->channels_mutex);
if (source)
obs_source_activate(source, AUX_VIEW);
if (prev_source) {
obs_source_deactivate(prev_source, AUX_VIEW);
obs_source_release(prev_source);
}
}
void obs_view_render(obs_view_t *view)
{
if (!view)
return;
pthread_mutex_lock(&view->channels_mutex);
for (size_t i = 0; i < MAX_CHANNELS; i++) {
struct obs_source *source;
source = view->channels[i];
if (source) {
if (source->removed) {
obs_source_release(source);
view->channels[i] = NULL;
} else {
obs_source_video_render(source);
}
}
}
pthread_mutex_unlock(&view->channels_mutex);
}
static inline size_t find_mix_for_view(obs_view_t *view)
{
for (size_t i = 0, num = obs->video.mixes.num; i < num; i++) {
if (obs->video.mixes.array[i]->view == view)
return i;
}
return DARRAY_INVALID;
}
static inline void set_main_mix()
{
size_t idx = find_mix_for_view(&obs->data.main_view);
struct obs_core_video_mix *mix = NULL;
if (idx != DARRAY_INVALID)
mix = obs->video.mixes.array[idx];
obs->video.main_mix = mix;
}
video_t *obs_view_add(obs_view_t *view)
{
if (!obs->video.main_mix)
return NULL;
return obs_view_add2(view, &obs->video.main_mix->ovi);
}
video_t *obs_view_add2(obs_view_t *view, struct obs_video_info *ovi)
{
if (!view || !ovi)
return NULL;
struct obs_core_video_mix *mix = obs_create_video_mix(ovi);
if (!mix) {
return NULL;
}
mix->view = view;
pthread_mutex_lock(&obs->video.mixes_mutex);
da_push_back(obs->video.mixes, &mix);
set_main_mix();
pthread_mutex_unlock(&obs->video.mixes_mutex);
return mix->video;
}
void obs_view_remove(obs_view_t *view)
{
if (!view)
return;
pthread_mutex_lock(&obs->video.mixes_mutex);
for (size_t i = 0, num = obs->video.mixes.num; i < num; i++) {
if (obs->video.mixes.array[i]->view == view)
obs->video.mixes.array[i]->view = NULL;
}
set_main_mix();
pthread_mutex_unlock(&obs->video.mixes_mutex);
}
bool obs_view_get_video_info(obs_view_t *view, struct obs_video_info *ovi)
{
if (!view)
return false;
pthread_mutex_lock(&obs->video.mixes_mutex);
size_t idx = find_mix_for_view(view);
if (idx != DARRAY_INVALID) {
*ovi = obs->video.mixes.array[idx]->ovi;
pthread_mutex_unlock(&obs->video.mixes_mutex);
return true;
}
pthread_mutex_unlock(&obs->video.mixes_mutex);
return false;
}
void obs_view_enum_video_info(obs_view_t *view, bool (*enum_proc)(void *, struct obs_video_info *), void *param)
{
pthread_mutex_lock(&obs->video.mixes_mutex);
for (size_t i = 0, num = obs->video.mixes.num; i < num; i++) {
struct obs_core_video_mix *mix = obs->video.mixes.array[i];
if (mix->view != view)
continue;
if (!enum_proc(param, &mix->ovi))
break;
}
pthread_mutex_unlock(&obs->video.mixes_mutex);
}
| 5,358 |
C
|
.c
| 183 | 26.721311 | 112 | 0.679157 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,032 |
obs-hevc.c
|
obsproject_obs-studio/libobs/obs-hevc.c
|
/******************************************************************************
Copyright (C) 2023 by Lain Bailey <[email protected]>
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/>.
******************************************************************************/
#include "obs-hevc.h"
#include "obs.h"
#include "obs-nal.h"
#include "util/array-serializer.h"
bool obs_hevc_keyframe(const uint8_t *data, size_t size)
{
const uint8_t *nal_start, *nal_end;
const uint8_t *end = data + size;
nal_start = obs_nal_find_startcode(data, end);
while (true) {
while (nal_start < end && !*(nal_start++))
;
if (nal_start == end)
break;
const uint8_t type = (nal_start[0] & 0x7F) >> 1;
if (type <= OBS_HEVC_NAL_RSV_IRAP_VCL23)
return type >= OBS_HEVC_NAL_BLA_W_LP;
nal_end = obs_nal_find_startcode(nal_start, end);
nal_start = nal_end;
}
return false;
}
static int compute_hevc_keyframe_priority(const uint8_t *nal_start, bool *is_keyframe, int priority)
{
// HEVC contains NAL unit specifier at [6..1] bits of
// the byte next to the startcode 0x000001
const int type = (nal_start[0] & 0x7F) >> 1;
// Mark IDR slices as key-frames and set them to highest
// priority if needed. Assume other slices are non-key
// frames and set their priority as high
if (type >= OBS_HEVC_NAL_BLA_W_LP && type <= OBS_HEVC_NAL_RSV_IRAP_VCL23) {
*is_keyframe = 1;
priority = OBS_NAL_PRIORITY_HIGHEST;
} else if (type >= OBS_HEVC_NAL_TRAIL_N && type <= OBS_HEVC_NAL_RASL_R) {
if (priority < OBS_NAL_PRIORITY_HIGH)
priority = OBS_NAL_PRIORITY_HIGH;
}
return priority;
}
static void serialize_hevc_data(struct serializer *s, const uint8_t *data, size_t size, bool *is_keyframe,
int *priority)
{
const uint8_t *const end = data + size;
const uint8_t *nal_start = obs_nal_find_startcode(data, end);
while (true) {
while (nal_start < end && !*(nal_start++))
;
if (nal_start == end)
break;
*priority = compute_hevc_keyframe_priority(nal_start, is_keyframe, *priority);
const uint8_t *const nal_end = obs_nal_find_startcode(nal_start, end);
const size_t nal_size = nal_end - nal_start;
s_wb32(s, (uint32_t)nal_size);
s_write(s, nal_start, nal_size);
nal_start = nal_end;
}
}
void obs_parse_hevc_packet(struct encoder_packet *hevc_packet, const struct encoder_packet *src)
{
struct array_output_data output;
struct serializer s;
long ref = 1;
array_output_serializer_init(&s, &output);
*hevc_packet = *src;
serialize(&s, &ref, sizeof(ref));
serialize_hevc_data(&s, src->data, src->size, &hevc_packet->keyframe, &hevc_packet->priority);
hevc_packet->data = output.bytes.array + sizeof(ref);
hevc_packet->size = output.bytes.num - sizeof(ref);
hevc_packet->drop_priority = hevc_packet->priority;
}
int obs_parse_hevc_packet_priority(const struct encoder_packet *packet)
{
int priority = packet->priority;
const uint8_t *const data = packet->data;
const uint8_t *const end = data + packet->size;
const uint8_t *nal_start = obs_nal_find_startcode(data, end);
while (true) {
while (nal_start < end && !*(nal_start++))
;
if (nal_start == end)
break;
bool unused;
priority = compute_hevc_keyframe_priority(nal_start, &unused, priority);
nal_start = obs_nal_find_startcode(nal_start, end);
}
return priority;
}
void obs_extract_hevc_headers(const uint8_t *packet, size_t size, uint8_t **new_packet_data, size_t *new_packet_size,
uint8_t **header_data, size_t *header_size, uint8_t **sei_data, size_t *sei_size)
{
DARRAY(uint8_t) new_packet;
DARRAY(uint8_t) header;
DARRAY(uint8_t) sei;
const uint8_t *nal_start, *nal_end, *nal_codestart;
const uint8_t *end = packet + size;
da_init(new_packet);
da_init(header);
da_init(sei);
nal_start = obs_nal_find_startcode(packet, end);
nal_end = NULL;
while (nal_end != end) {
nal_codestart = nal_start;
while (nal_start < end && !*(nal_start++))
;
if (nal_start == end)
break;
const uint8_t type = (nal_start[0] & 0x7F) >> 1;
nal_end = obs_nal_find_startcode(nal_start, end);
if (!nal_end)
nal_end = end;
if (type == OBS_HEVC_NAL_VPS || type == OBS_HEVC_NAL_SPS || type == OBS_HEVC_NAL_PPS) {
da_push_back_array(header, nal_codestart, nal_end - nal_codestart);
} else if (type == OBS_HEVC_NAL_SEI_PREFIX || type == OBS_HEVC_NAL_SEI_SUFFIX) {
da_push_back_array(sei, nal_codestart, nal_end - nal_codestart);
} else {
da_push_back_array(new_packet, nal_codestart, nal_end - nal_codestart);
}
nal_start = nal_end;
}
*new_packet_data = new_packet.array;
*new_packet_size = new_packet.num;
*header_data = header.array;
*header_size = header.num;
*sei_data = sei.array;
*sei_size = sei.num;
}
| 5,301 |
C
|
.c
| 139 | 35.266187 | 117 | 0.676103 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,042 |
array-serializer.c
|
obsproject_obs-studio/libobs/util/array-serializer.c
|
/*
* Copyright (c) 2023 Lain Bailey <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "darray.h"
#include "array-serializer.h"
static size_t array_output_write(void *param, const void *data, size_t size)
{
struct array_output_data *output = param;
if (output->cur_pos < output->bytes.num) {
size_t new_size = output->cur_pos + size;
if (new_size > output->bytes.num) {
darray_ensure_capacity(sizeof(uint8_t), &output->bytes.da, new_size);
output->bytes.num = new_size;
}
memcpy(output->bytes.array + output->cur_pos, data, size);
output->cur_pos += size;
} else {
da_push_back_array(output->bytes, (uint8_t *)data, size);
output->cur_pos += size;
}
return size;
}
static int64_t array_output_get_pos(void *param)
{
struct array_output_data *data = param;
return (int64_t)data->bytes.num;
}
static int64_t array_output_seek(void *param, int64_t offset, enum serialize_seek_type seek_type)
{
struct array_output_data *output = param;
size_t new_pos = 0;
switch (seek_type) {
case SERIALIZE_SEEK_START:
new_pos = offset;
break;
case SERIALIZE_SEEK_CURRENT:
new_pos = output->cur_pos + offset;
break;
case SERIALIZE_SEEK_END:
new_pos = output->bytes.num - offset;
break;
}
if (new_pos > output->bytes.num)
return -1;
output->cur_pos = new_pos;
return (int64_t)new_pos;
}
void array_output_serializer_init(struct serializer *s, struct array_output_data *data)
{
memset(s, 0, sizeof(struct serializer));
memset(data, 0, sizeof(struct array_output_data));
s->data = data;
s->write = array_output_write;
s->get_pos = array_output_get_pos;
s->seek = array_output_seek;
}
void array_output_serializer_free(struct array_output_data *data)
{
da_free(data->bytes);
}
void array_output_serializer_reset(struct array_output_data *data)
{
da_clear(data->bytes);
data->cur_pos = 0;
}
| 2,558 |
C
|
.c
| 77 | 31.051948 | 97 | 0.735903 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,045 |
pipe-posix.c
|
obsproject_obs-studio/libobs/util/pipe-posix.c
|
/*
* Copyright (c) 2023 Lain Bailey <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
#include <spawn.h>
#include <fcntl.h>
#include "bmem.h"
#include "pipe.h"
struct os_process_pipe {
bool read_pipe;
int pid;
FILE *file;
FILE *err_file;
};
os_process_pipe_t *os_process_pipe_create_internal(const char *bin, char **argv, const char *type)
{
struct os_process_pipe process_pipe = {0};
struct os_process_pipe *out;
posix_spawn_file_actions_t file_actions;
if (!bin || !argv || !type) {
return NULL;
}
process_pipe.read_pipe = *type == 'r';
int mainfds[2] = {0};
int errfds[2] = {0};
if (pipe(mainfds) != 0) {
return NULL;
}
if (pipe(errfds) != 0) {
close(mainfds[0]);
close(mainfds[1]);
return NULL;
}
if (posix_spawn_file_actions_init(&file_actions) != 0) {
close(mainfds[0]);
close(mainfds[1]);
close(errfds[0]);
close(errfds[1]);
return NULL;
}
fcntl(mainfds[0], F_SETFD, FD_CLOEXEC);
fcntl(mainfds[1], F_SETFD, FD_CLOEXEC);
fcntl(errfds[0], F_SETFD, FD_CLOEXEC);
fcntl(errfds[1], F_SETFD, FD_CLOEXEC);
if (process_pipe.read_pipe) {
posix_spawn_file_actions_addclose(&file_actions, mainfds[0]);
if (mainfds[1] != STDOUT_FILENO) {
posix_spawn_file_actions_adddup2(&file_actions, mainfds[1], STDOUT_FILENO);
posix_spawn_file_actions_addclose(&file_actions, mainfds[0]);
}
} else {
if (mainfds[0] != STDIN_FILENO) {
posix_spawn_file_actions_adddup2(&file_actions, mainfds[0], STDIN_FILENO);
posix_spawn_file_actions_addclose(&file_actions, mainfds[1]);
}
}
posix_spawn_file_actions_addclose(&file_actions, errfds[0]);
posix_spawn_file_actions_adddup2(&file_actions, errfds[1], STDERR_FILENO);
int pid;
int ret = posix_spawn(&pid, bin, &file_actions, NULL, (char *const *)argv, NULL);
posix_spawn_file_actions_destroy(&file_actions);
if (ret != 0) {
close(mainfds[0]);
close(mainfds[1]);
close(errfds[0]);
close(errfds[1]);
return NULL;
}
close(errfds[1]);
process_pipe.err_file = fdopen(errfds[0], "r");
if (process_pipe.read_pipe) {
close(mainfds[1]);
process_pipe.file = fdopen(mainfds[0], "r");
} else {
close(mainfds[0]);
process_pipe.file = fdopen(mainfds[1], "w");
}
process_pipe.pid = pid;
out = bmalloc(sizeof(os_process_pipe_t));
*out = process_pipe;
return out;
}
os_process_pipe_t *os_process_pipe_create(const char *cmd_line, const char *type)
{
if (!cmd_line)
return NULL;
char *argv[3] = {"-c", (char *)cmd_line, NULL};
return os_process_pipe_create_internal("/bin/sh", argv, type);
}
os_process_pipe_t *os_process_pipe_create2(const os_process_args_t *args, const char *type)
{
char **argv = os_process_args_get_argv(args);
return os_process_pipe_create_internal(argv[0], argv, type);
}
int os_process_pipe_destroy(os_process_pipe_t *pp)
{
int ret = 0;
if (pp) {
int status;
fclose(pp->file);
pp->file = NULL;
fclose(pp->err_file);
pp->err_file = NULL;
do {
ret = waitpid(pp->pid, &status, 0);
} while (ret == -1 && errno == EINTR);
if (WIFEXITED(status))
ret = (int)(char)WEXITSTATUS(status);
bfree(pp);
}
return ret;
}
size_t os_process_pipe_read(os_process_pipe_t *pp, uint8_t *data, size_t len)
{
if (!pp) {
return 0;
}
if (!pp->read_pipe) {
return 0;
}
return fread(data, 1, len, pp->file);
}
size_t os_process_pipe_read_err(os_process_pipe_t *pp, uint8_t *data, size_t len)
{
if (!pp) {
return 0;
}
return fread(data, 1, len, pp->err_file);
}
size_t os_process_pipe_write(os_process_pipe_t *pp, const uint8_t *data, size_t len)
{
if (!pp) {
return 0;
}
if (pp->read_pipe) {
return 0;
}
size_t written = 0;
while (written < len) {
size_t ret = fwrite(data + written, 1, len - written, pp->file);
if (!ret)
return written;
written += ret;
}
return written;
}
| 4,574 |
C
|
.c
| 161 | 26.012422 | 98 | 0.692431 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,047 |
pipe.c
|
obsproject_obs-studio/libobs/util/pipe.c
|
/*
* Copyright (c) 2023 Dennis Sädtler <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "pipe.h"
#include "darray.h"
#include "dstr.h"
struct os_process_args {
DARRAY(char *) arguments;
};
struct os_process_args *os_process_args_create(const char *executable)
{
struct os_process_args *args = bzalloc(sizeof(struct os_process_args));
char *str = bstrdup(executable);
da_push_back(args->arguments, &str);
/* Last item in argv must be NULL. */
char *terminator = NULL;
da_push_back(args->arguments, &terminator);
return args;
}
void os_process_args_add_arg(struct os_process_args *args, const char *arg)
{
char *str = bstrdup(arg);
/* Insert before NULL list terminator. */
da_insert(args->arguments, args->arguments.num - 1, &str);
}
void os_process_args_add_argf(struct os_process_args *args, const char *format, ...)
{
va_list va_args;
struct dstr tmp = {0};
va_start(va_args, format);
dstr_vprintf(&tmp, format, va_args);
da_insert(args->arguments, args->arguments.num - 1, &tmp.array);
va_end(va_args);
}
size_t os_process_args_get_argc(struct os_process_args *args)
{
/* Do not count terminating NULL. */
return args->arguments.num - 1;
}
char **os_process_args_get_argv(const struct os_process_args *args)
{
return args->arguments.array;
}
void os_process_args_destroy(struct os_process_args *args)
{
if (!args)
return;
for (size_t idx = 0; idx < args->arguments.num; idx++)
bfree(args->arguments.array[idx]);
da_free(args->arguments);
bfree(args);
}
| 2,214 |
C
|
.c
| 64 | 32.765625 | 84 | 0.743338 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,058 |
buffered-file-serializer.c
|
obsproject_obs-studio/libobs/util/buffered-file-serializer.c
|
/*
* Copyright (c) 2024 Dennis Sädtler <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "buffered-file-serializer.h"
#include <inttypes.h>
#include "platform.h"
#include "threading.h"
#include "deque.h"
#include "dstr.h"
static const size_t DEFAULT_BUF_SIZE = 256ULL * 1048576ULL; // 256 MiB
static const size_t DEFAULT_CHUNK_SIZE = 1048576; // 1 MiB
/* ========================================================================== */
/* Buffered writer based on ffmpeg-mux implementation */
struct io_header {
uint64_t seek_offset;
uint64_t data_length;
};
struct io_buffer {
bool active;
bool shutdown_requested;
bool output_error;
os_event_t *buffer_space_available_event;
os_event_t *new_data_available_event;
pthread_t io_thread;
pthread_mutex_t data_mutex;
FILE *output_file;
struct deque data;
uint64_t next_pos;
size_t buffer_size;
size_t chunk_size;
};
struct file_output_data {
struct dstr filename;
struct io_buffer io;
};
static void *io_thread(void *opaque)
{
struct file_output_data *out = opaque;
os_set_thread_name("buffered writer i/o thread");
// Chunk collects the writes into a larger batch
size_t chunk_used = 0;
size_t chunk_size = out->io.chunk_size;
unsigned char *chunk = bmalloc(chunk_size);
if (!chunk) {
os_atomic_set_bool(&out->io.output_error, true);
fprintf(stderr, "Error allocating memory for output\n");
goto error;
}
bool shutting_down;
bool want_seek = false;
bool force_flush_chunk = false;
// current_seek_position is a virtual position updated as we read from
// the buffer, if it becomes discontinuous due to a seek request we
// flush the chunk. next_seek_position is the actual offset we should
// seek to when we write the chunk.
uint64_t current_seek_position = 0;
uint64_t next_seek_position;
for (;;) {
// Wait for data to be written to the buffer
os_event_wait(out->io.new_data_available_event);
// Loop to write in chunk_size chunks
for (;;) {
pthread_mutex_lock(&out->io.data_mutex);
shutting_down = os_atomic_load_bool(&out->io.shutdown_requested);
// Fetch as many writes as possible from the deque
// and fill up our local chunk. This may involve
// seeking, so take care of that as well.
for (;;) {
size_t available = out->io.data.size;
// Buffer is empty (now) or was already empty (we got
// woken up to exit)
if (!available)
break;
// Get seek offset and data size
struct io_header header;
deque_peek_front(&out->io.data, &header, sizeof(header));
// Do we need to seek?
if (header.seek_offset != current_seek_position) {
// If there's already part of a chunk pending,
// flush it at the current offset. Similarly,
// if we already plan to seek, then seek.
if (chunk_used || want_seek) {
force_flush_chunk = true;
break;
}
// Mark that we need to seek and where to
want_seek = true;
next_seek_position = header.seek_offset;
// Update our virtual position
current_seek_position = header.seek_offset;
}
// Make sure there's enough room for the data, if
// not then force a flush
if (header.data_length + chunk_used > chunk_size) {
force_flush_chunk = true;
break;
}
// Remove header that we already read
deque_pop_front(&out->io.data, NULL, sizeof(header));
// Copy from the buffer to our local chunk
deque_pop_front(&out->io.data, chunk + chunk_used, header.data_length);
// Update offsets
chunk_used += header.data_length;
current_seek_position += header.data_length;
}
// Signal that there is more room in the buffer
os_event_signal(out->io.buffer_space_available_event);
// Try to avoid lots of small writes unless this was the final
// data left in the buffer. The buffer might be entirely empty
// if we were woken up to exit.
if (!force_flush_chunk && (!chunk_used || (chunk_used < 65536 && !shutting_down))) {
os_event_reset(out->io.new_data_available_event);
pthread_mutex_unlock(&out->io.data_mutex);
break;
}
pthread_mutex_unlock(&out->io.data_mutex);
// Seek if we need to
if (want_seek) {
os_fseeki64(out->io.output_file, next_seek_position, SEEK_SET);
// Update the next virtual position, making sure to take
// into account the size of the chunk we're about to write.
current_seek_position = next_seek_position + chunk_used;
want_seek = false;
// If we did a seek but do not have any data left to write
// return to the start of the loop.
if (!chunk_used) {
force_flush_chunk = false;
continue;
}
}
// Write the current chunk to the output file
size_t bytes_written = fwrite(chunk, 1, chunk_used, out->io.output_file);
if (bytes_written != chunk_used) {
blog(LOG_ERROR, "Error writing to '%s': %s (%zu != %zu)\n", out->filename.array,
strerror(errno), bytes_written, chunk_used);
os_atomic_set_bool(&out->io.output_error, true);
goto error;
}
chunk_used = 0;
force_flush_chunk = false;
}
// If this was the last chunk, time to exit
if (shutting_down)
break;
}
error:
if (chunk)
bfree(chunk);
fclose(out->io.output_file);
return NULL;
}
/* ========================================================================== */
/* Serializer Implementation */
static int64_t file_output_seek(void *opaque, int64_t offset, enum serialize_seek_type seek_type)
{
struct file_output_data *out = opaque;
// If the output thread failed, signal that back up the stack
if (os_atomic_load_bool(&out->io.output_error))
return -1;
// Update where the next write should go
pthread_mutex_lock(&out->io.data_mutex);
switch (seek_type) {
case SERIALIZE_SEEK_START:
out->io.next_pos = offset;
break;
case SERIALIZE_SEEK_CURRENT:
out->io.next_pos += offset;
break;
case SERIALIZE_SEEK_END:
out->io.next_pos -= offset;
break;
}
pthread_mutex_unlock(&out->io.data_mutex);
return (int64_t)out->io.next_pos;
}
#ifndef _WIN32
static inline size_t max(size_t a, size_t b)
{
return a > b ? a : b;
}
static inline size_t min(size_t a, size_t b)
{
return a < b ? a : b;
}
#endif
static size_t file_output_write(void *opaque, const void *buf, size_t buf_size)
{
struct file_output_data *out = opaque;
if (!buf_size)
return 0;
// Split writes into at chunks that are at most chunk_size bytes
uintptr_t ptr = (uintptr_t)buf;
size_t remaining = buf_size;
while (remaining) {
if (os_atomic_load_bool(&out->io.output_error))
return 0;
pthread_mutex_lock(&out->io.data_mutex);
size_t next_chunk_size = min(remaining, out->io.chunk_size);
// Avoid unbounded growth of the deque, cap to buffer_size
size_t cap = max(out->io.data.capacity, out->io.buffer_size);
size_t free_space = cap - out->io.data.size;
if (free_space < next_chunk_size + sizeof(struct io_header)) {
blog(LOG_DEBUG, "Waiting for I/O thread...");
// No space, wait for the I/O thread to make space
os_event_reset(out->io.buffer_space_available_event);
pthread_mutex_unlock(&out->io.data_mutex);
os_event_wait(out->io.buffer_space_available_event);
continue;
}
// Calculate how many chunks we can fit into the buffer
size_t num_chunks = free_space / (next_chunk_size + sizeof(struct io_header));
while (remaining && num_chunks--) {
struct io_header header = {
.data_length = next_chunk_size,
.seek_offset = out->io.next_pos,
};
// Copy the data into the buffer
deque_push_back(&out->io.data, &header, sizeof(header));
deque_push_back(&out->io.data, (const void *)ptr, next_chunk_size);
// Advance the next write position
out->io.next_pos += next_chunk_size;
// Update remainder and advance data pointer
remaining -= next_chunk_size;
ptr += next_chunk_size;
next_chunk_size = min(remaining, out->io.chunk_size);
}
// Tell the I/O thread that there's new data to be written
os_event_signal(out->io.new_data_available_event);
pthread_mutex_unlock(&out->io.data_mutex);
}
return buf_size - remaining;
}
static int64_t file_output_get_pos(void *opaque)
{
struct file_output_data *out = opaque;
// If thread failed return -1
if (os_atomic_load_bool(&out->io.output_error))
return -1;
return (int64_t)out->io.next_pos;
}
bool buffered_file_serializer_init_defaults(struct serializer *s, const char *path)
{
return buffered_file_serializer_init(s, path, 0, 0);
}
bool buffered_file_serializer_init(struct serializer *s, const char *path, size_t max_bufsize, size_t chunk_size)
{
struct file_output_data *out;
out = bzalloc(sizeof(*out));
dstr_init_copy(&out->filename, path);
out->io.output_file = os_fopen(path, "wb");
if (!out->io.output_file)
return false;
out->io.buffer_size = max_bufsize ? max_bufsize : DEFAULT_BUF_SIZE;
out->io.chunk_size = chunk_size ? chunk_size : DEFAULT_CHUNK_SIZE;
// Start at 1MB, this can grow up to max_bufsize depending
// on how fast data is going in and out.
deque_reserve(&out->io.data, 1048576);
pthread_mutex_init(&out->io.data_mutex, NULL);
os_event_init(&out->io.buffer_space_available_event, OS_EVENT_TYPE_AUTO);
os_event_init(&out->io.new_data_available_event, OS_EVENT_TYPE_AUTO);
pthread_create(&out->io.io_thread, NULL, io_thread, out);
out->io.active = true;
s->data = out;
s->read = NULL;
s->write = file_output_write;
s->seek = file_output_seek;
s->get_pos = file_output_get_pos;
return true;
}
void buffered_file_serializer_free(struct serializer *s)
{
struct file_output_data *out = s->data;
if (!out)
return;
if (out->io.active) {
os_atomic_set_bool(&out->io.shutdown_requested, true);
// Wakes up the I/O thread and waits for it to finish
pthread_mutex_lock(&out->io.data_mutex);
os_event_signal(out->io.new_data_available_event);
pthread_mutex_unlock(&out->io.data_mutex);
pthread_join(out->io.io_thread, NULL);
os_event_destroy(out->io.new_data_available_event);
os_event_destroy(out->io.buffer_space_available_event);
pthread_mutex_destroy(&out->io.data_mutex);
blog(LOG_DEBUG, "Final buffer capacity: %zu KiB", out->io.data.capacity / 1024);
deque_free(&out->io.data);
}
dstr_free(&out->filename);
bfree(out);
}
| 11,004 |
C
|
.c
| 302 | 33.225166 | 113 | 0.689155 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,072 |
device-enum.c
|
obsproject_obs-studio/libobs/util/windows/device-enum.c
|
#include "device-enum.h"
#include "../dstr.h"
#include <dxgi.h>
void enum_graphics_device_luids(device_luid_cb device_luid, void *param)
{
IDXGIFactory1 *factory;
IDXGIAdapter1 *adapter;
HRESULT hr;
hr = CreateDXGIFactory1(&IID_IDXGIFactory1, (void **)&factory);
if (FAILED(hr))
return;
for (UINT i = 0; factory->lpVtbl->EnumAdapters1(factory, i, &adapter) == S_OK; i++) {
DXGI_ADAPTER_DESC desc;
hr = adapter->lpVtbl->GetDesc(adapter, &desc);
adapter->lpVtbl->Release(adapter);
if (FAILED(hr))
continue;
uint64_t luid64 = *(uint64_t *)&desc.AdapterLuid;
if (!device_luid(param, i, luid64))
break;
}
factory->lpVtbl->Release(factory);
}
| 672 |
C
|
.c
| 23 | 26.695652 | 86 | 0.707165 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,098 |
graphics-ffmpeg.c
|
obsproject_obs-studio/libobs/graphics/graphics-ffmpeg.c
|
#include "graphics.h"
#include "half.h"
#include "srgb.h"
#include <obs-ffmpeg-compat.h>
#include <util/dstr.h>
#include <util/platform.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/imgutils.h>
#include <libswscale/swscale.h>
#ifdef _WIN32
#include <wincodec.h>
#pragma comment(lib, "windowscodecs.lib")
#endif
struct ffmpeg_image {
const char *file;
AVFormatContext *fmt_ctx;
AVCodecContext *decoder_ctx;
int cx, cy;
enum AVPixelFormat format;
};
static bool ffmpeg_image_open_decoder_context(struct ffmpeg_image *info)
{
AVFormatContext *const fmt_ctx = info->fmt_ctx;
int ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, 1, NULL, 0);
if (ret < 0) {
blog(LOG_WARNING, "Couldn't find video stream in file '%s': %s", info->file, av_err2str(ret));
return false;
}
AVStream *const stream = fmt_ctx->streams[ret];
AVCodecParameters *const codecpar = stream->codecpar;
const AVCodec *const decoder = avcodec_find_decoder(codecpar->codec_id); // fix discarded-qualifiers
if (!decoder) {
blog(LOG_WARNING, "Failed to find decoder for file '%s'", info->file);
return false;
}
AVCodecContext *const decoder_ctx = avcodec_alloc_context3(decoder);
avcodec_parameters_to_context(decoder_ctx, codecpar);
info->decoder_ctx = decoder_ctx;
info->cx = codecpar->width;
info->cy = codecpar->height;
info->format = codecpar->format;
ret = avcodec_open2(decoder_ctx, decoder, NULL);
if (ret < 0) {
blog(LOG_WARNING,
"Failed to open video codec for file '%s': "
"%s",
info->file, av_err2str(ret));
return false;
}
return true;
}
static void ffmpeg_image_free(struct ffmpeg_image *info)
{
avcodec_free_context(&info->decoder_ctx);
avformat_close_input(&info->fmt_ctx);
}
static bool ffmpeg_image_init(struct ffmpeg_image *info, const char *file)
{
int ret;
if (!file || !*file)
return false;
memset(info, 0, sizeof(struct ffmpeg_image));
info->file = file;
ret = avformat_open_input(&info->fmt_ctx, file, NULL, NULL);
if (ret < 0) {
blog(LOG_WARNING, "Failed to open file '%s': %s", info->file, av_err2str(ret));
return false;
}
ret = avformat_find_stream_info(info->fmt_ctx, NULL);
if (ret < 0) {
blog(LOG_WARNING,
"Could not find stream info for file '%s':"
" %s",
info->file, av_err2str(ret));
goto fail;
}
if (!ffmpeg_image_open_decoder_context(info))
goto fail;
return true;
fail:
ffmpeg_image_free(info);
return false;
}
#ifdef _MSC_VER
#define obs_bswap16(v) _byteswap_ushort(v)
#else
#define obs_bswap16(v) __builtin_bswap16(v)
#endif
static void *ffmpeg_image_copy_data_straight(struct ffmpeg_image *info, AVFrame *frame)
{
const size_t linesize = (size_t)info->cx * 4;
const size_t totalsize = info->cy * linesize;
void *data = bmalloc(totalsize);
const size_t src_linesize = frame->linesize[0];
if (linesize != src_linesize) {
const size_t min_line = linesize < src_linesize ? linesize : src_linesize;
uint8_t *dst = data;
const uint8_t *src = frame->data[0];
for (int y = 0; y < info->cy; y++) {
memcpy(dst, src, min_line);
dst += linesize;
src += src_linesize;
}
} else {
memcpy(data, frame->data[0], totalsize);
}
return data;
}
static inline size_t get_dst_position(const size_t w, const size_t h, const size_t x, const size_t y, int orient)
{
size_t res_x = 0;
size_t res_y = 0;
if (orient == 2) {
/*
* Orientation 2: Flip X
*
* 888888 888888
* 88 -> 88
* 8888 -> 8888
* 88 -> 88
* 88 88
*
* (0, 0) -> (w, 0)
* (0, h) -> (w, h)
* (w, 0) -> (0, 0)
* (w, h) -> (0, h)
*
* (w - x, y)
*/
res_x = w - 1 - x;
res_y = y;
} else if (orient == 3) {
/*
* Orientation 3: 180 degree
*
* 88 888888
* 88 -> 88
* 8888 -> 8888
* 88 -> 88
* 888888 88
*
* (0, 0) -> (w, h)
* (0, h) -> (w, 0)
* (w, 0) -> (0, h)
* (w, h) -> (0, 0)
*
* (w - x, h - y)
*/
res_x = w - 1 - x;
res_y = h - 1 - y;
} else if (orient == 4) {
/*
* Orientation 4: Flip Y
*
* 88 888888
* 88 -> 88
* 8888 -> 8888
* 88 -> 88
* 888888 88
*
* (0, 0) -> (0, h)
* (0, h) -> (0, 0)
* (w, 0) -> (w, h)
* (w, h) -> (w, 0)
*
* (x, h - y)
*/
res_x = x;
res_y = h - 1 - y;
} else if (orient == 5) {
/*
* Orientation 5: Flip Y + 90 degree CW
*
* 8888888888 888888
* 88 88 -> 88
* 88 -> 8888
* -> 88
* 88
*
* (0, 0) -> (0, 0)
* (0, h) -> (w, 0)
* (w, 0) -> (0, h)
* (w, h) -> (w, h)
*
* (y, x)
*/
res_x = y;
res_y = x;
} else if (orient == 6) {
/*
* Orientation 6: 90 degree CW
*
* 88 888888
* 88 88 -> 88
* 8888888888 -> 8888
* -> 88
* 88
*
* (0, 0) -> (w, 0)
* (0, h) -> (0, 0)
* (w, 0) -> (w, h)
* (w, h) -> (0, h)
*
* (w - y, x)
*/
res_x = w - 1 - y;
res_y = x;
} else if (orient == 7) {
/*
* Orientation 7: Flip Y + 90 degree CCW
*
* 88 888888
* 88 88 -> 88
* 8888888888 -> 8888
* -> 88
* 88
*
* (0, 0) -> (w, h)
* (0, h) -> (0, h)
* (w, 0) -> (w, 0)
* (w, h) -> (0, 0)
*
* (w - y, h - x)
*/
res_x = w - 1 - y;
res_y = h - 1 - x;
} else if (orient == 8) {
/*
* Orientation 8: 90 degree CCW
*
* 8888888888 888888
* 88 88 -> 88
* 88 -> 8888
* -> 88
* 88
*
* (0, 0) -> (0, h)
* (0, h) -> (w, h)
* (w, 0) -> (0, 0)
* (w, h) -> (w, 0)
*
* (y, h - x)
*/
res_x = y;
res_y = h - 1 - x;
}
return (res_x + res_y * w) * 4;
}
#define TILE_SIZE 16
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
static void *ffmpeg_image_orient(struct ffmpeg_image *info, void *in_data, int orient)
{
const size_t sx = (size_t)info->cx;
const size_t sy = (size_t)info->cy;
uint8_t *data = NULL;
if (orient == 0 || orient == 1)
return in_data;
data = bmalloc(sx * 4 * sy);
if (orient >= 5 && orient < 9) {
info->cx = (int)sy;
info->cy = (int)sx;
}
uint8_t *src = in_data;
size_t off_dst;
size_t off_src = 0;
for (size_t y0 = 0; y0 < sy; y0 += TILE_SIZE) {
for (size_t x0 = 0; x0 < sx; x0 += TILE_SIZE) {
size_t lim_x = MIN((size_t)sx, x0 + TILE_SIZE);
size_t lim_y = MIN((size_t)sy, y0 + TILE_SIZE);
for (size_t y = y0; y < lim_y; y++) {
for (size_t x = x0; x < lim_x; x++) {
off_src = (x + y * sx) * 4;
off_dst = get_dst_position(info->cx, info->cy, x, y, orient);
memcpy(data + off_dst, src + off_src, 4);
}
}
}
}
bfree(in_data);
return data;
}
static void *ffmpeg_image_reformat_frame(struct ffmpeg_image *info, AVFrame *frame, enum gs_image_alpha_mode alpha_mode)
{
struct SwsContext *sws_ctx = NULL;
void *data = NULL;
int ret = 0;
AVDictionary *dict = frame->metadata;
AVDictionaryEntry *entry = NULL;
int orient = 0;
if (dict) {
entry = av_dict_get(dict, "Orientation", NULL, AV_DICT_MATCH_CASE);
if (entry && entry->value) {
orient = atoi(entry->value);
}
}
if (info->format == AV_PIX_FMT_BGR0) {
data = ffmpeg_image_copy_data_straight(info, frame);
} else if (info->format == AV_PIX_FMT_RGBA || info->format == AV_PIX_FMT_BGRA) {
if (alpha_mode == GS_IMAGE_ALPHA_STRAIGHT) {
data = ffmpeg_image_copy_data_straight(info, frame);
} else {
const size_t linesize = (size_t)info->cx * 4;
const size_t totalsize = info->cy * linesize;
data = bmalloc(totalsize);
const size_t src_linesize = frame->linesize[0];
const size_t min_line = linesize < src_linesize ? linesize : src_linesize;
uint8_t *dst = data;
const uint8_t *src = frame->data[0];
const size_t row_elements = min_line >> 2;
if (alpha_mode == GS_IMAGE_ALPHA_PREMULTIPLY_SRGB) {
for (int y = 0; y < info->cy; y++) {
gs_premultiply_xyza_srgb_loop_restrict(dst, src, row_elements);
dst += linesize;
src += src_linesize;
}
} else if (alpha_mode == GS_IMAGE_ALPHA_PREMULTIPLY) {
for (int y = 0; y < info->cy; y++) {
gs_premultiply_xyza_loop_restrict(dst, src, row_elements);
dst += linesize;
src += src_linesize;
}
}
}
} else if (info->format == AV_PIX_FMT_RGBA64BE) {
const size_t dst_linesize = (size_t)info->cx * 4;
data = bmalloc(info->cy * dst_linesize);
const size_t src_linesize = frame->linesize[0];
const size_t src_min_line = (dst_linesize * 2) < src_linesize ? (dst_linesize * 2) : src_linesize;
const size_t row_elements = src_min_line >> 3;
uint8_t *dst = data;
const uint8_t *src = frame->data[0];
uint16_t value[4];
float f[4];
if (alpha_mode == GS_IMAGE_ALPHA_STRAIGHT) {
for (int y = 0; y < info->cy; y++) {
for (size_t x = 0; x < row_elements; ++x) {
memcpy(value, src, sizeof(value));
f[0] = (float)obs_bswap16(value[0]) / 65535.0f;
f[1] = (float)obs_bswap16(value[1]) / 65535.0f;
f[2] = (float)obs_bswap16(value[2]) / 65535.0f;
f[3] = (float)obs_bswap16(value[3]) / 65535.0f;
gs_float4_to_u8x4(dst, f);
dst += sizeof(*dst) * 4;
src += sizeof(value);
}
src += src_linesize - src_min_line;
}
} else if (alpha_mode == GS_IMAGE_ALPHA_PREMULTIPLY_SRGB) {
for (int y = 0; y < info->cy; y++) {
for (size_t x = 0; x < row_elements; ++x) {
memcpy(value, src, sizeof(value));
f[0] = (float)obs_bswap16(value[0]) / 65535.0f;
f[1] = (float)obs_bswap16(value[1]) / 65535.0f;
f[2] = (float)obs_bswap16(value[2]) / 65535.0f;
f[3] = (float)obs_bswap16(value[3]) / 65535.0f;
gs_float3_srgb_nonlinear_to_linear(f);
gs_premultiply_float4(f);
gs_float3_srgb_linear_to_nonlinear(f);
gs_float4_to_u8x4(dst, f);
dst += sizeof(*dst) * 4;
src += sizeof(value);
}
src += src_linesize - src_min_line;
}
} else if (alpha_mode == GS_IMAGE_ALPHA_PREMULTIPLY) {
for (int y = 0; y < info->cy; y++) {
for (size_t x = 0; x < row_elements; ++x) {
memcpy(value, src, sizeof(value));
f[0] = (float)obs_bswap16(value[0]) / 65535.0f;
f[1] = (float)obs_bswap16(value[1]) / 65535.0f;
f[2] = (float)obs_bswap16(value[2]) / 65535.0f;
f[3] = (float)obs_bswap16(value[3]) / 65535.0f;
gs_premultiply_float4(f);
gs_float4_to_u8x4(dst, f);
dst += sizeof(*dst) * 4;
src += sizeof(value);
}
src += src_linesize - src_min_line;
}
}
info->format = AV_PIX_FMT_RGBA;
} else {
static const enum AVPixelFormat format = AV_PIX_FMT_BGRA;
sws_ctx = sws_getContext(info->cx, info->cy, info->format, info->cx, info->cy, format, SWS_POINT, NULL,
NULL, NULL);
if (!sws_ctx) {
blog(LOG_WARNING,
"Failed to create scale context "
"for '%s'",
info->file);
goto fail;
}
uint8_t *pointers[4];
int linesizes[4];
ret = av_image_alloc(pointers, linesizes, info->cx, info->cy, format, 32);
if (ret < 0) {
blog(LOG_WARNING, "av_image_alloc failed for '%s': %s", info->file, av_err2str(ret));
sws_freeContext(sws_ctx);
goto fail;
}
ret = sws_scale(sws_ctx, (const uint8_t *const *)frame->data, frame->linesize, 0, info->cy, pointers,
linesizes);
sws_freeContext(sws_ctx);
if (ret < 0) {
blog(LOG_WARNING, "sws_scale failed for '%s': %s", info->file, av_err2str(ret));
av_freep(pointers);
goto fail;
}
const size_t linesize = (size_t)info->cx * 4;
data = bmalloc(info->cy * linesize);
const uint8_t *src = pointers[0];
uint8_t *dst = data;
for (size_t y = 0; y < (size_t)info->cy; y++) {
memcpy(dst, src, linesize);
dst += linesize;
src += linesizes[0];
}
av_freep(pointers);
if (alpha_mode == GS_IMAGE_ALPHA_PREMULTIPLY_SRGB) {
gs_premultiply_xyza_srgb_loop(data, (size_t)info->cx * info->cy);
} else if (alpha_mode == GS_IMAGE_ALPHA_PREMULTIPLY) {
gs_premultiply_xyza_loop(data, (size_t)info->cx * info->cy);
}
info->format = format;
}
data = ffmpeg_image_orient(info, data, orient);
fail:
return data;
}
static void *ffmpeg_image_decode(struct ffmpeg_image *info, enum gs_image_alpha_mode alpha_mode)
{
AVPacket packet = {0};
void *data = NULL;
AVFrame *frame = av_frame_alloc();
int got_frame = 0;
int ret;
if (!frame) {
blog(LOG_WARNING, "Failed to create frame data for '%s'", info->file);
return NULL;
}
ret = av_read_frame(info->fmt_ctx, &packet);
if (ret < 0) {
blog(LOG_WARNING, "Failed to read image frame from '%s': %s", info->file, av_err2str(ret));
goto fail;
}
while (!got_frame) {
ret = avcodec_send_packet(info->decoder_ctx, &packet);
if (ret == 0)
ret = avcodec_receive_frame(info->decoder_ctx, frame);
got_frame = (ret == 0);
if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
ret = 0;
if (ret < 0) {
blog(LOG_WARNING, "Failed to decode frame for '%s': %s", info->file, av_err2str(ret));
goto fail;
}
}
data = ffmpeg_image_reformat_frame(info, frame, alpha_mode);
fail:
av_packet_unref(&packet);
av_frame_free(&frame);
return data;
}
void gs_init_image_deps(void) {}
void gs_free_image_deps(void) {}
static inline enum gs_color_format convert_format(enum AVPixelFormat format)
{
switch (format) {
case AV_PIX_FMT_RGBA:
return GS_RGBA;
case AV_PIX_FMT_BGRA:
return GS_BGRA;
case AV_PIX_FMT_BGR0:
return GS_BGRX;
case AV_PIX_FMT_RGBA64BE:
return GS_RGBA16;
default:
return GS_BGRX;
}
}
uint8_t *gs_create_texture_file_data(const char *file, enum gs_color_format *format, uint32_t *cx_out, uint32_t *cy_out)
{
struct ffmpeg_image image;
uint8_t *data = NULL;
if (ffmpeg_image_init(&image, file)) {
data = ffmpeg_image_decode(&image, GS_IMAGE_ALPHA_STRAIGHT);
if (data) {
*format = convert_format(image.format);
*cx_out = (uint32_t)image.cx;
*cy_out = (uint32_t)image.cy;
}
ffmpeg_image_free(&image);
}
return data;
}
#ifdef _WIN32
static float pq_to_linear(float u)
{
const float common = powf(u, 1.f / 78.84375f);
return powf(fabsf(max(common - 0.8359375f, 0.f) / (18.8515625f - 18.6875f * common)), 1.f / 0.1593017578f);
}
static void convert_pq_to_cccs(const BYTE *intermediate, const UINT intermediate_size, BYTE *bytes)
{
const BYTE *src_cursor = intermediate;
const BYTE *src_cursor_end = src_cursor + intermediate_size;
BYTE *dst_cursor = bytes;
uint32_t rgb10;
struct half rgba16[4];
rgba16[3].u = 0x3c00;
while (src_cursor < src_cursor_end) {
memcpy(&rgb10, src_cursor, sizeof(rgb10));
const float blue = (float)(rgb10 & 0x3ff) / 1023.f;
const float green = (float)((rgb10 >> 10) & 0x3ff) / 1023.f;
const float red = (float)((rgb10 >> 20) & 0x3ff) / 1023.f;
const float red2020 = pq_to_linear(red);
const float green2020 = pq_to_linear(green);
const float blue2020 = pq_to_linear(blue);
const float red709 = 1.6604910021084345f * red2020 - 0.58764113878854951f * green2020 -
0.072849863319884883f * blue2020;
const float green709 = -0.12455047452159074f * red2020 + 1.1328998971259603f * green2020 -
0.0083494226043694768f * blue2020;
const float blue709 = -0.018150763354905303f * red2020 - 0.10057889800800739f * green2020 +
1.1187296613629127f * blue2020;
rgba16[0] = half_from_float(red709 * 125.f);
rgba16[1] = half_from_float(green709 * 125.f);
rgba16[2] = half_from_float(blue709 * 125.f);
memcpy(dst_cursor, &rgba16, sizeof(rgba16));
src_cursor += 4;
dst_cursor += 8;
}
}
static void *wic_image_init_internal(const char *file, IWICBitmapFrameDecode *pFrame, enum gs_color_format *format,
uint32_t *cx_out, uint32_t *cy_out, enum gs_color_space *space)
{
BYTE *bytes = NULL;
WICPixelFormatGUID pixelFormat;
HRESULT hr = pFrame->lpVtbl->GetPixelFormat(pFrame, &pixelFormat);
if (SUCCEEDED(hr)) {
const bool scrgb = memcmp(&pixelFormat, &GUID_WICPixelFormat64bppRGBAHalf, sizeof(pixelFormat)) == 0;
const bool pq10 = memcmp(&pixelFormat, &GUID_WICPixelFormat32bppBGR101010, sizeof(pixelFormat)) == 0;
if (scrgb || pq10) {
UINT width, height;
hr = pFrame->lpVtbl->GetSize(pFrame, &width, &height);
if (SUCCEEDED(hr)) {
const UINT pitch = 8 * width;
const UINT size = pitch * height;
bytes = bmalloc(size);
if (bytes) {
bool success = false;
if (pq10) {
const UINT intermediate_pitch = 4 * width;
const UINT intermediate_size = intermediate_pitch * height;
BYTE *intermediate = bmalloc(intermediate_size);
if (intermediate) {
hr = pFrame->lpVtbl->CopyPixels(pFrame, NULL,
intermediate_pitch,
intermediate_size,
intermediate);
success = SUCCEEDED(hr);
if (success) {
convert_pq_to_cccs(intermediate, intermediate_size,
bytes);
} else {
blog(LOG_WARNING,
"WIC: Failed to CopyPixels intermediate for file: %s",
file);
}
bfree(intermediate);
} else {
blog(LOG_WARNING,
"WIC: Failed to allocate intermediate for file: %s", file);
}
} else {
hr = pFrame->lpVtbl->CopyPixels(pFrame, NULL, pitch, size, bytes);
success = SUCCEEDED(hr);
if (!success) {
blog(LOG_WARNING, "WIC: Failed to CopyPixels for file: %s",
file);
}
}
if (success) {
*format = GS_RGBA16F;
*cx_out = width;
*cy_out = height;
*space = GS_CS_709_SCRGB;
} else {
bfree(bytes);
bytes = NULL;
}
} else {
blog(LOG_WARNING, "WIC: Failed to allocate for file: %s", file);
}
} else {
blog(LOG_WARNING, "WIC: Failed to GetSize of frame for file: %s", file);
}
} else {
blog(LOG_WARNING,
"WIC: Only handle GUID_WICPixelFormat32bppBGR101010 and GUID_WICPixelFormat64bppRGBAHalf for now");
}
} else {
blog(LOG_WARNING, "WIC: Failed to GetPixelFormat for file: %s", file);
}
return bytes;
}
static void *wic_image_init(const struct ffmpeg_image *info, const char *file, enum gs_color_format *format,
uint32_t *cx_out, uint32_t *cy_out, enum gs_color_space *space)
{
const size_t len = strlen(file);
if (len <= 4 && astrcmpi(file + len - 4, ".jxr") != 0) {
blog(LOG_WARNING, "WIC: Only handle JXR for WIC images for now");
return NULL;
}
BYTE *bytes = NULL;
wchar_t *file_w = NULL;
os_utf8_to_wcs_ptr(file, 0, &file_w);
if (file_w) {
IWICImagingFactory *pFactory = NULL;
HRESULT hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER,
&IID_IWICImagingFactory, &pFactory);
if (SUCCEEDED(hr)) {
IWICBitmapDecoder *pDecoder = NULL;
hr = pFactory->lpVtbl->CreateDecoderFromFilename(pFactory, file_w, NULL, GENERIC_READ,
WICDecodeMetadataCacheOnDemand, &pDecoder);
if (SUCCEEDED(hr)) {
IWICBitmapFrameDecode *pFrame = NULL;
hr = pDecoder->lpVtbl->GetFrame(pDecoder, 0, &pFrame);
if (SUCCEEDED(hr)) {
bytes = wic_image_init_internal(file, pFrame, format, cx_out, cy_out, space);
pFrame->lpVtbl->Release(pFrame);
} else {
blog(LOG_WARNING, "WIC: Failed to create IWICBitmapFrameDecode from file: %s",
file);
}
pDecoder->lpVtbl->Release(pDecoder);
} else {
blog(LOG_WARNING, "WIC: Failed to create IWICBitmapDecoder from file: %s", file);
}
pFactory->lpVtbl->Release(pFactory);
} else {
blog(LOG_WARNING, "WIC: Failed to create IWICImagingFactory");
}
bfree(file_w);
} else {
blog(LOG_WARNING, "WIC: Failed to widen file name: %s", file);
}
return bytes;
}
#endif
uint8_t *gs_create_texture_file_data2(const char *file, enum gs_image_alpha_mode alpha_mode,
enum gs_color_format *format, uint32_t *cx_out, uint32_t *cy_out)
{
enum gs_color_space unused;
return gs_create_texture_file_data3(file, alpha_mode, format, cx_out, cy_out, &unused);
}
uint8_t *gs_create_texture_file_data3(const char *file, enum gs_image_alpha_mode alpha_mode,
enum gs_color_format *format, uint32_t *cx_out, uint32_t *cy_out,
enum gs_color_space *space)
{
struct ffmpeg_image image;
uint8_t *data = NULL;
if (ffmpeg_image_init(&image, file)) {
data = ffmpeg_image_decode(&image, alpha_mode);
if (data) {
*format = convert_format(image.format);
*cx_out = (uint32_t)image.cx;
*cy_out = (uint32_t)image.cy;
*space = GS_CS_SRGB;
}
ffmpeg_image_free(&image);
}
#ifdef _WIN32
if (data == NULL) {
data = wic_image_init(&image, file, format, cx_out, cy_out, space);
}
#endif
return data;
}
| 20,634 |
C
|
.c
| 678 | 26.684366 | 120 | 0.611931 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,149 |
video-matrices.c
|
obsproject_obs-studio/libobs/media-io/video-matrices.c
|
/******************************************************************************
Copyright (C) 2014 by Ruwen Hahn <[email protected]>
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/>.
******************************************************************************/
#include "video-io.h"
#include "../util/bmem.h"
#include "../graphics/matrix3.h"
#include <assert.h>
//#define LOG_MATRICES
static struct {
float range_min[3];
float range_max[3];
float black_levels[2][3];
float float_range_min[3];
float float_range_max[3];
} bpp_info[9];
static struct {
enum video_colorspace const color_space;
float const Kb, Kr;
float matrix[OBS_COUNTOF(bpp_info)][2][16];
} format_info[] = {
{
VIDEO_CS_601,
0.114f,
0.299f,
},
{
VIDEO_CS_709,
0.0722f,
0.2126f,
},
{
VIDEO_CS_2100_PQ,
0.0593f,
0.2627f,
},
};
#define NUM_FORMATS (sizeof(format_info) / sizeof(format_info[0]))
#ifdef LOG_MATRICES
static void log_matrix(float const matrix[16])
{
blog(LOG_DEBUG,
"\n% f, % f, % f, % f"
"\n% f, % f, % f, % f"
"\n% f, % f, % f, % f"
"\n% f, % f, % f, % f",
matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], matrix[6], matrix[7], matrix[8],
matrix[9], matrix[10], matrix[11], matrix[12], matrix[13], matrix[14], matrix[15]);
}
#endif
static void initialize_matrix(float const Kb, float const Kr, float bit_range_max, float const range_min[3],
float const range_max[3], float const black_levels[3], float matrix[16])
{
struct matrix3 color_matrix;
float const yvals = range_max[0] - range_min[0];
float const uvals = (range_max[1] - range_min[1]) / 2.f;
float const vvals = (range_max[2] - range_min[2]) / 2.f;
float const yscale = bit_range_max / yvals;
float const uscale = bit_range_max / uvals;
float const vscale = bit_range_max / vvals;
float const Kg = (1.f - Kb - Kr);
vec3_set(&color_matrix.x, yscale, 0.f, vscale * (1.f - Kr));
vec3_set(&color_matrix.y, yscale, uscale * (Kb - 1.f) * Kb / Kg, vscale * (Kr - 1.f) * Kr / Kg);
vec3_set(&color_matrix.z, yscale, uscale * (1.f - Kb), 0.f);
struct vec3 offsets, multiplied;
vec3_set(&offsets, -black_levels[0] / bit_range_max, -black_levels[1] / bit_range_max,
-black_levels[2] / bit_range_max);
vec3_rotate(&multiplied, &offsets, &color_matrix);
matrix[0] = color_matrix.x.x;
matrix[1] = color_matrix.x.y;
matrix[2] = color_matrix.x.z;
matrix[3] = multiplied.x;
matrix[4] = color_matrix.y.x;
matrix[5] = color_matrix.y.y;
matrix[6] = color_matrix.y.z;
matrix[7] = multiplied.y;
matrix[8] = color_matrix.z.x;
matrix[9] = color_matrix.z.y;
matrix[10] = color_matrix.z.z;
matrix[11] = multiplied.z;
matrix[12] = matrix[13] = matrix[14] = 0.;
matrix[15] = 1.;
#ifdef LOG_MATRICES
log_matrix(matrix);
#endif
}
static void initialize_matrices()
{
static const float full_range_min3[] = {0, 0, 0};
float min_value = 16.f;
float max_luma = 235.f;
float max_chroma = 240.f;
float range = 256.f;
for (uint32_t bpp = 8; bpp <= 16; ++bpp) {
const uint32_t bpp_index = bpp - 8;
bpp_info[bpp_index].range_min[0] = min_value;
bpp_info[bpp_index].range_min[1] = min_value;
bpp_info[bpp_index].range_min[2] = min_value;
bpp_info[bpp_index].range_max[0] = max_luma;
bpp_info[bpp_index].range_max[1] = max_chroma;
bpp_info[bpp_index].range_max[2] = max_chroma;
const float mid_chroma = 0.5f * (min_value + max_chroma);
bpp_info[bpp_index].black_levels[0][0] = min_value;
bpp_info[bpp_index].black_levels[0][1] = mid_chroma;
bpp_info[bpp_index].black_levels[0][2] = mid_chroma;
bpp_info[bpp_index].black_levels[1][0] = 0.f;
bpp_info[bpp_index].black_levels[1][1] = mid_chroma;
bpp_info[bpp_index].black_levels[1][2] = mid_chroma;
const float range_max = range - 1.f;
bpp_info[bpp_index].float_range_min[0] = min_value / range_max;
bpp_info[bpp_index].float_range_min[1] = min_value / range_max;
bpp_info[bpp_index].float_range_min[2] = min_value / range_max;
bpp_info[bpp_index].float_range_max[0] = max_luma / range_max;
bpp_info[bpp_index].float_range_max[1] = max_chroma / range_max;
bpp_info[bpp_index].float_range_max[2] = max_chroma / range_max;
for (size_t i = 0; i < NUM_FORMATS; i++) {
float full_range_max3[] = {range_max, range_max, range_max};
initialize_matrix(format_info[i].Kb, format_info[i].Kr, range_max, full_range_min3,
full_range_max3, bpp_info[bpp_index].black_levels[1],
format_info[i].matrix[bpp_index][1]);
initialize_matrix(format_info[i].Kb, format_info[i].Kr, range_max,
bpp_info[bpp_index].range_min, bpp_info[bpp_index].range_max,
bpp_info[bpp_index].black_levels[0], format_info[i].matrix[bpp_index][0]);
}
min_value *= 2.f;
max_luma *= 2.f;
max_chroma *= 2.f;
range *= 2.f;
}
}
static bool matrices_initialized = false;
static const float full_min[3] = {0.0f, 0.0f, 0.0f};
static const float full_max[3] = {1.0f, 1.0f, 1.0f};
static bool video_format_get_parameters_for_bpc(enum video_colorspace color_space, enum video_range_type range,
float matrix[16], float range_min[3], float range_max[3], uint32_t bpc)
{
if (!matrices_initialized) {
initialize_matrices();
matrices_initialized = true;
}
if ((color_space == VIDEO_CS_DEFAULT) || (color_space == VIDEO_CS_SRGB))
color_space = VIDEO_CS_709;
else if (color_space == VIDEO_CS_2100_HLG)
color_space = VIDEO_CS_2100_PQ;
if (bpc < 8)
bpc = 8;
if (bpc > 16)
bpc = 16;
const uint32_t bpc_index = bpc - 8;
assert(bpc_index < OBS_COUNTOF(bpp_info));
bool success = false;
for (size_t i = 0; i < NUM_FORMATS; i++) {
success = format_info[i].color_space == color_space;
if (success) {
const bool full_range = range == VIDEO_RANGE_FULL;
memcpy(matrix, format_info[i].matrix[bpc_index][full_range], sizeof(float) * 16);
if (range_min) {
const float *src_range_min = full_range ? full_min
: bpp_info[bpc_index].float_range_min;
memcpy(range_min, src_range_min, sizeof(float) * 3);
}
if (range_max) {
const float *src_range_max = full_range ? full_max
: bpp_info[bpc_index].float_range_max;
memcpy(range_max, src_range_max, sizeof(float) * 3);
}
break;
}
}
return success;
}
bool video_format_get_parameters(enum video_colorspace color_space, enum video_range_type range, float matrix[16],
float range_min[3], float range_max[3])
{
uint32_t bpc = (color_space == VIDEO_CS_2100_PQ || color_space == VIDEO_CS_2100_HLG) ? 10 : 8;
return video_format_get_parameters_for_bpc(color_space, range, matrix, range_min, range_max, bpc);
}
bool video_format_get_parameters_for_format(enum video_colorspace color_space, enum video_range_type range,
enum video_format format, float matrix[16], float range_min[3],
float range_max[3])
{
uint32_t bpc;
switch (format) {
case VIDEO_FORMAT_I010:
case VIDEO_FORMAT_P010:
case VIDEO_FORMAT_I210:
case VIDEO_FORMAT_V210:
case VIDEO_FORMAT_R10L:
bpc = 10;
break;
case VIDEO_FORMAT_I412:
case VIDEO_FORMAT_YA2L:
bpc = 12;
break;
case VIDEO_FORMAT_P216:
case VIDEO_FORMAT_P416:
bpc = 16;
break;
default:
bpc = 8;
break;
}
return video_format_get_parameters_for_bpc(color_space, range, matrix, range_min, range_max, bpc);
}
| 7,853 |
C
|
.c
| 213 | 33.798122 | 114 | 0.66342 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,153 |
video-frame.c
|
obsproject_obs-studio/libobs/media-io/video-frame.c
|
/******************************************************************************
Copyright (C) 2023 by Lain Bailey <[email protected]>
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/>.
******************************************************************************/
#include <assert.h>
#include "video-frame.h"
#define HALF(size) ((size + 1) / 2)
#define ALIGN(size, alignment) *size = (*size + alignment - 1) & (~(alignment - 1));
static inline void align_size(size_t *size, size_t alignment)
{
ALIGN(size, alignment);
}
static inline void align_uint32(uint32_t *size, size_t alignment)
{
ALIGN(size, (uint32_t)alignment);
}
/* assumes already-zeroed array */
void video_frame_get_linesizes(uint32_t linesize[MAX_AV_PLANES], enum video_format format, uint32_t width)
{
switch (format) {
default:
case VIDEO_FORMAT_NONE:
break;
case VIDEO_FORMAT_BGR3: /* one plane: triple width */
linesize[0] = width * 3;
break;
case VIDEO_FORMAT_RGBA: /* one plane: quadruple width */
case VIDEO_FORMAT_BGRA:
case VIDEO_FORMAT_BGRX:
case VIDEO_FORMAT_AYUV:
case VIDEO_FORMAT_R10L:
linesize[0] = width * 4;
break;
case VIDEO_FORMAT_P416: /* two planes: double width, quadruple width */
linesize[0] = width * 2;
linesize[1] = width * 4;
break;
case VIDEO_FORMAT_I420: /* three planes: full width, half width, half width */
case VIDEO_FORMAT_I422:
linesize[0] = width;
linesize[1] = HALF(width);
linesize[2] = HALF(width);
break;
case VIDEO_FORMAT_I210: /* three planes: double width, full width, full width */
case VIDEO_FORMAT_I010:
linesize[0] = width * 2;
linesize[1] = width;
linesize[2] = width;
break;
case VIDEO_FORMAT_I40A: /* four planes: full width, half width, half width, full width */
case VIDEO_FORMAT_I42A:
linesize[0] = width;
linesize[1] = HALF(width);
linesize[2] = HALF(width);
linesize[3] = width;
break;
case VIDEO_FORMAT_YVYU: /* one plane: double width */
case VIDEO_FORMAT_YUY2:
case VIDEO_FORMAT_UYVY:
linesize[0] = width * 2;
break;
case VIDEO_FORMAT_P010: /* two planes: all double width */
case VIDEO_FORMAT_P216:
linesize[0] = width * 2;
linesize[1] = width * 2;
break;
case VIDEO_FORMAT_I412: /* three planes: all double width */
linesize[0] = width * 2;
linesize[1] = width * 2;
linesize[2] = width * 2;
break;
case VIDEO_FORMAT_YA2L: /* four planes: all double width */
linesize[0] = width * 2;
linesize[1] = width * 2;
linesize[2] = width * 2;
linesize[3] = width * 2;
break;
case VIDEO_FORMAT_Y800: /* one plane: full width */
linesize[0] = width;
break;
case VIDEO_FORMAT_NV12: /* two planes: all full width */
linesize[0] = width;
linesize[1] = width;
break;
case VIDEO_FORMAT_I444: /* three planes: all full width */
linesize[0] = width;
linesize[1] = width;
linesize[2] = width;
break;
case VIDEO_FORMAT_YUVA: /* four planes: all full width */
linesize[0] = width;
linesize[1] = width;
linesize[2] = width;
linesize[3] = width;
break;
case VIDEO_FORMAT_V210: { /* one plane: bruh (Little Endian Compressed) */
align_uint32(&width, 48);
linesize[0] = ((width + 5) / 6) * 16;
break;
}
}
}
void video_frame_get_plane_heights(uint32_t heights[MAX_AV_PLANES], enum video_format format, uint32_t height)
{
switch (format) {
default:
case VIDEO_FORMAT_NONE:
return;
case VIDEO_FORMAT_I420: /* three planes: full height, half height, half height */
case VIDEO_FORMAT_I010:
heights[0] = height;
heights[1] = HALF(height);
heights[2] = HALF(height);
break;
case VIDEO_FORMAT_NV12: /* two planes: full height, half height */
case VIDEO_FORMAT_P010:
heights[0] = height;
heights[1] = HALF(height);
break;
case VIDEO_FORMAT_Y800: /* one plane: full height */
case VIDEO_FORMAT_YVYU:
case VIDEO_FORMAT_YUY2:
case VIDEO_FORMAT_UYVY:
case VIDEO_FORMAT_RGBA:
case VIDEO_FORMAT_BGRA:
case VIDEO_FORMAT_BGRX:
case VIDEO_FORMAT_BGR3:
case VIDEO_FORMAT_AYUV:
case VIDEO_FORMAT_V210:
case VIDEO_FORMAT_R10L:
heights[0] = height;
break;
case VIDEO_FORMAT_I444: /* three planes: all full height */
case VIDEO_FORMAT_I422:
case VIDEO_FORMAT_I210:
case VIDEO_FORMAT_I412:
heights[0] = height;
heights[1] = height;
heights[2] = height;
break;
case VIDEO_FORMAT_I40A: /* four planes: full height, half height, half height, full height */
heights[0] = height;
heights[1] = HALF(height);
heights[2] = HALF(height);
heights[3] = height;
break;
case VIDEO_FORMAT_I42A: /* four planes: all full height */
case VIDEO_FORMAT_YUVA:
case VIDEO_FORMAT_YA2L:
heights[0] = height;
heights[1] = height;
heights[2] = height;
heights[3] = height;
break;
case VIDEO_FORMAT_P216: /* two planes: all full height */
case VIDEO_FORMAT_P416:
heights[0] = height;
heights[1] = height;
break;
}
}
void video_frame_init(struct video_frame *frame, enum video_format format, uint32_t width, uint32_t height)
{
size_t size = 0;
uint32_t linesizes[MAX_AV_PLANES];
uint32_t heights[MAX_AV_PLANES];
size_t offsets[MAX_AV_PLANES];
int alignment = base_get_alignment();
if (!frame)
return;
memset(frame, 0, sizeof(struct video_frame));
memset(linesizes, 0, sizeof(linesizes));
memset(heights, 0, sizeof(heights));
memset(offsets, 0, sizeof(offsets));
/* determine linesizes for each plane */
video_frame_get_linesizes(linesizes, format, width);
/* determine line count for each plane */
video_frame_get_plane_heights(heights, format, height);
/* calculate total buffer required */
for (uint32_t i = 0; i < MAX_AV_PLANES; i++) {
if (!linesizes[i] || !heights[i])
continue;
size_t plane_size = (size_t)linesizes[i] * (size_t)heights[i];
align_size(&plane_size, alignment);
size += plane_size;
offsets[i] = size;
}
/* allocate memory */
frame->data[0] = bmalloc(size);
frame->linesize[0] = linesizes[0];
/* apply plane data pointers according to offsets */
for (uint32_t i = 1; i < MAX_AV_PLANES; i++) {
if (!linesizes[i] || !heights[i])
continue;
frame->data[i] = frame->data[0] + offsets[i - 1];
frame->linesize[i] = linesizes[i];
}
}
void video_frame_copy(struct video_frame *dst, const struct video_frame *src, enum video_format format, uint32_t cy)
{
uint32_t heights[MAX_AV_PLANES];
memset(heights, 0, sizeof(heights));
/* determine line count for each plane */
video_frame_get_plane_heights(heights, format, cy);
/* copy each plane */
for (uint32_t i = 0; i < MAX_AV_PLANES; i++) {
if (!heights[i])
continue;
if (src->linesize[i] == dst->linesize[i]) {
memcpy(dst->data[i], src->data[i], src->linesize[i] * heights[i]);
} else { /* linesizes which do not match must be copied line-by-line */
size_t src_linesize = src->linesize[i];
size_t dst_linesize = dst->linesize[i];
/* determine how much we can write (frames with different line sizes require more )*/
size_t linesize = src_linesize < dst_linesize ? src_linesize : dst_linesize;
for (uint32_t y = 0; y < heights[i]; y++) {
uint8_t *src_pos = src->data[i] + (src_linesize * y);
uint8_t *dst_pos = dst->data[i] + (dst_linesize * y);
memcpy(dst_pos, src_pos, linesize);
}
}
}
}
| 7,749 |
C
|
.c
| 232 | 30.711207 | 116 | 0.680871 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,172 |
test_os_path.c
|
obsproject_obs-studio/test/cmocka/test_os_path.c
|
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <util/platform.h>
struct testcase {
const char *path;
const char *ext;
};
static void run_testcases(struct testcase *testcases)
{
for (size_t i = 0; testcases[i].path; i++) {
const char *path = testcases[i].path;
const char *ext = os_get_path_extension(path);
printf("path: '%s' ext: '%s'\n", path, ext);
if (testcases[i].ext)
assert_string_equal(ext, testcases[i].ext);
else
assert_ptr_equal(ext, testcases[i].ext);
}
}
static void os_get_path_extension_test(void **state)
{
UNUSED_PARAMETER(state);
static struct testcase testcases[] = {{"/home/user/a.txt", ".txt"},
{"C:\\Users\\user\\Documents\\video.mp4", ".mp4"},
{"./\\", NULL},
{".\\/", NULL},
{"/.\\", NULL},
{"/\\.", "."},
{"\\/.", "."},
{"\\./", NULL},
{"", NULL},
{NULL, NULL}};
run_testcases(testcases);
}
int main()
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(os_get_path_extension_test),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
| 1,145 |
C
|
.c
| 43 | 22.44186 | 68 | 0.587912 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,183 |
service-ingest.h
|
obsproject_obs-studio/plugins/rtmp-services/service-specific/service-ingest.h
|
#pragma once
/* service-ingest.h is common between the Amazon IVS service
* and the Twitch streaming service.
*/
#include <file-updater/file-updater.h>
#include <util/threading.h>
struct ingest {
char *name;
char *url;
char *rtmps_url;
};
struct service_ingests {
update_info_t *update_info;
pthread_mutex_t mutex;
bool ingests_refreshed;
bool ingests_refreshing;
bool ingests_loaded;
DARRAY(struct ingest) cur_ingests;
const char *cache_old_filename;
const char *cache_new_filename;
};
void init_service_data(struct service_ingests *si);
void service_ingests_refresh(struct service_ingests *si, int seconds, const char *log_prefix, const char *file_url);
void load_service_data(struct service_ingests *si, const char *cache_filename, struct ingest *def);
void unload_service_data(struct service_ingests *si);
struct ingest get_ingest(struct service_ingests *si, size_t idx);
| 893 |
C
|
.c
| 26 | 32.692308 | 116 | 0.782155 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,184 |
twitch.h
|
obsproject_obs-studio/plugins/rtmp-services/service-specific/twitch.h
|
#pragma once
#include "service-ingest.h"
extern void twitch_ingests_lock(void);
extern void twitch_ingests_unlock(void);
extern size_t twitch_ingest_count(void);
extern struct ingest twitch_ingest(size_t idx);
| 212 |
C
|
.c
| 6 | 34 | 47 | 0.808824 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,186 |
amazon-ivs.c
|
obsproject_obs-studio/plugins/rtmp-services/service-specific/amazon-ivs.c
|
#include "service-ingest.h"
#include "amazon-ivs.h"
static struct service_ingests amazon_ivs = {.update_info = NULL,
.mutex = PTHREAD_MUTEX_INITIALIZER,
.ingests_refreshed = false,
.ingests_refreshing = false,
.ingests_loaded = false,
.cur_ingests = {0},
.cache_old_filename = "amazon_ivs_ingests.json",
.cache_new_filename = "amazon_ivs_ingests.new.json"};
void init_amazon_ivs_data(void)
{
init_service_data(&amazon_ivs);
}
void load_amazon_ivs_data(void)
{
struct ingest def = {.name = bstrdup("Default"),
.url = bstrdup("rtmps://ingest.global-contribute.live-video.net:443/app/")};
load_service_data(&amazon_ivs, "amazon_ivs_ingests.json", &def);
}
void unload_amazon_ivs_data(void)
{
unload_service_data(&amazon_ivs);
}
void amazon_ivs_ingests_refresh(int seconds)
{
service_ingests_refresh(&amazon_ivs, seconds, "[amazon ivs ingest update] ",
"https://ingest.contribute.live-video.net/ingests");
}
void amazon_ivs_ingests_lock(void)
{
pthread_mutex_lock(&amazon_ivs.mutex);
}
void amazon_ivs_ingests_unlock(void)
{
pthread_mutex_unlock(&amazon_ivs.mutex);
}
size_t amazon_ivs_ingest_count(void)
{
return amazon_ivs.cur_ingests.num;
}
struct ingest amazon_ivs_ingest(size_t idx)
{
return get_ingest(&amazon_ivs, idx);
}
| 1,318 |
C
|
.c
| 45 | 26.222222 | 84 | 0.710443 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,187 |
service-ingest.c
|
obsproject_obs-studio/plugins/rtmp-services/service-specific/service-ingest.c
|
#include <util/platform.h>
#include <obs-module.h>
#include <util/dstr.h>
#include <jansson.h>
#include "service-ingest.h"
extern const char *get_module_name(void);
void init_service_data(struct service_ingests *si)
{
da_init(si->cur_ingests);
pthread_mutex_init(&si->mutex, NULL);
}
static void free_ingests(struct service_ingests *si)
{
for (size_t i = 0; i < si->cur_ingests.num; i++) {
struct ingest *ingest = si->cur_ingests.array + i;
bfree(ingest->name);
bfree(ingest->url);
bfree(ingest->rtmps_url);
}
da_free(si->cur_ingests);
}
static bool load_ingests(struct service_ingests *si, const char *json, bool write_file)
{
json_t *root;
json_t *ingests;
bool success = false;
char *cache_old;
char *cache_new;
size_t count;
root = json_loads(json, 0, NULL);
if (!root)
goto finish;
ingests = json_object_get(root, "ingests");
if (!ingests)
goto finish;
count = json_array_size(ingests);
if (count <= 1 && si->cur_ingests.num)
goto finish;
free_ingests(si);
for (size_t i = 0; i < count; i++) {
json_t *item = json_array_get(ingests, i);
json_t *item_name = json_object_get(item, "name");
json_t *item_url = json_object_get(item, "url_template");
json_t *item_rtmps_url = json_object_get(item, "url_template_secure");
struct ingest ingest = {0};
struct dstr url = {0};
struct dstr rtmps_url = {0};
if (!item_name || !item_url)
continue;
const char *url_str = json_string_value(item_url);
const char *rtmps_url_str = json_string_value(item_rtmps_url);
const char *name_str = json_string_value(item_name);
/* At the moment they currently mis-spell "deprecated",
* but that may change in the future, so blacklist both */
if (strstr(name_str, "deprecated") != NULL || strstr(name_str, "depracated") != NULL)
continue;
dstr_copy(&url, url_str);
dstr_replace(&url, "/{stream_key}", "");
dstr_copy(&rtmps_url, rtmps_url_str);
dstr_replace(&rtmps_url, "/{stream_key}", "");
ingest.name = bstrdup(name_str);
ingest.url = url.array;
ingest.rtmps_url = rtmps_url.array;
da_push_back(si->cur_ingests, &ingest);
}
if (!si->cur_ingests.num)
goto finish;
success = true;
if (!write_file)
goto finish;
cache_old = obs_module_config_path(si->cache_old_filename);
cache_new = obs_module_config_path(si->cache_new_filename);
os_quick_write_utf8_file(cache_new, json, strlen(json), false);
os_safe_replace(cache_old, cache_new, NULL);
bfree(cache_old);
bfree(cache_new);
finish:
if (root)
json_decref(root);
return success;
}
static bool ingest_update(void *param, struct file_download_data *data)
{
struct service_ingests *service = param;
bool success;
pthread_mutex_lock(&service->mutex);
success = load_ingests(service, (const char *)data->buffer.array, true);
pthread_mutex_unlock(&service->mutex);
if (success) {
os_atomic_set_bool(&service->ingests_refreshed, true);
os_atomic_set_bool(&service->ingests_loaded, true);
}
return true;
}
void service_ingests_refresh(struct service_ingests *si, int seconds, const char *log_prefix, const char *file_url)
{
if (os_atomic_load_bool(&si->ingests_refreshed))
return;
if (!os_atomic_load_bool(&si->ingests_refreshing)) {
os_atomic_set_bool(&si->ingests_refreshing, true);
si->update_info = update_info_create_single(log_prefix, get_module_name(), file_url, ingest_update, si);
}
/* wait five seconds max when loading ingests for the first time */
if (!os_atomic_load_bool(&si->ingests_loaded)) {
for (int i = 0; i < seconds * 100; i++) {
if (os_atomic_load_bool(&si->ingests_refreshed)) {
break;
}
os_sleep_ms(10);
}
}
}
void load_service_data(struct service_ingests *si, const char *cache_filename, struct ingest *def)
{
char *service_cache = obs_module_config_path(cache_filename);
pthread_mutex_lock(&si->mutex);
da_push_back(si->cur_ingests, def);
pthread_mutex_unlock(&si->mutex);
if (os_file_exists(service_cache)) {
char *data = os_quick_read_utf8_file(service_cache);
bool success;
pthread_mutex_lock(&si->mutex);
success = load_ingests(si, data, false);
pthread_mutex_unlock(&si->mutex);
if (success) {
os_atomic_set_bool(&si->ingests_loaded, true);
}
bfree(data);
}
bfree(service_cache);
}
void unload_service_data(struct service_ingests *si)
{
update_info_destroy(si->update_info);
free_ingests(si);
pthread_mutex_destroy(&si->mutex);
}
struct ingest get_ingest(struct service_ingests *si, size_t idx)
{
struct ingest ingest;
if (si->cur_ingests.num <= idx) {
ingest.name = NULL;
ingest.url = NULL;
ingest.rtmps_url = NULL;
} else {
ingest = *(struct ingest *)(si->cur_ingests.array + idx);
}
return ingest;
}
| 4,683 |
C
|
.c
| 149 | 28.899329 | 115 | 0.702293 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,189 |
twitch.c
|
obsproject_obs-studio/plugins/rtmp-services/service-specific/twitch.c
|
#include "service-ingest.h"
#include "twitch.h"
static struct service_ingests twitch = {.update_info = NULL,
.mutex = PTHREAD_MUTEX_INITIALIZER,
.ingests_refreshed = false,
.ingests_refreshing = false,
.ingests_loaded = false,
.cur_ingests = {0},
.cache_old_filename = "twitch_ingests.json",
.cache_new_filename = "twitch_ingests.new.json"};
void twitch_ingests_lock(void)
{
pthread_mutex_lock(&twitch.mutex);
}
void twitch_ingests_unlock(void)
{
pthread_mutex_unlock(&twitch.mutex);
}
size_t twitch_ingest_count(void)
{
return twitch.cur_ingests.num;
}
struct ingest twitch_ingest(size_t idx)
{
return get_ingest(&twitch, idx);
}
void init_twitch_data(void)
{
init_service_data(&twitch);
}
void twitch_ingests_refresh(int seconds)
{
service_ingests_refresh(&twitch, seconds, "[twitch ingest update] ", "https://ingest.twitch.tv/ingests");
}
void load_twitch_data(void)
{
struct ingest def = {.name = bstrdup("Default"), .url = bstrdup("rtmp://live.twitch.tv/app")};
load_service_data(&twitch, "twitch_ingests.json", &def);
}
void unload_twitch_data(void)
{
unload_service_data(&twitch);
}
| 1,143 |
C
|
.c
| 43 | 24.348837 | 106 | 0.72594 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,349 |
nvidia-videofx-filter.c
|
obsproject_obs-studio/plugins/nv-filters/nvidia-videofx-filter.c
|
#include <obs-module.h>
#include <util/threading.h>
#include <dxgi.h>
#include <d3d11.h>
#include <d3d11_1.h>
#include "nvvfx-load.h"
/* -------------------------------------------------------- */
#define do_log(level, format, ...) \
blog(level, "[NVIDIA Video Effect: '%s'] " format, obs_source_get_name(filter->context), ##__VA_ARGS__)
#define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
#define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
#define error(format, ...) do_log(LOG_ERROR, format, ##__VA_ARGS__)
#ifdef _DEBUG
#define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
#else
#define debug(format, ...)
#endif
/* -------------------------------------------------------- */
#define S_MODE "mode"
#define S_MODE_QUALITY 0
#define S_MODE_PERF 1
#define S_THRESHOLDFX "threshold"
#define S_THRESHOLDFX_DEFAULT 1.0
#define S_PROCESSING "processing_interval"
#define MT_ obs_module_text
#define TEXT_MODE MT_("Nvvfx.Method.Greenscreen.Mode")
#define TEXT_MODE_QUALITY MT_("Nvvfx.Method.Greenscreen.Quality")
#define TEXT_MODE_PERF MT_("Nvvfx.Method.Greenscreen.Performance")
#define TEXT_MODE_THRESHOLD MT_("Nvvfx.Method.Greenscreen.Threshold")
#define TEXT_DEPRECATION MT_("Nvvfx.OutdatedSDK")
#define TEXT_PROCESSING MT_("Nvvfx.Method.Greenscreen.Processing")
#define TEXT_PROCESSING_HINT MT_("Nvvfx.Method.Greenscreen.Processing.Hint")
/* Blur & background blur FX */
#define S_STRENGTH "intensity"
#define S_STRENGTH_DEFAULT 0.5
#define TEXT_MODE_BLUR_STRENGTH MT_("Nvvfx.Method.Blur.Strength")
enum nvvfx_filter_id { S_FX_AIGS, S_FX_BLUR, S_FX_BG_BLUR };
bool nvvfx_loaded = false;
bool nvvfx_new_sdk = false;
/* clang-format off */
struct nvvfx_data {
obs_source_t *context;
bool images_allocated;
bool initial_render;
volatile bool processing_stop;
bool processed_frame;
bool target_valid;
bool got_new_frame;
signal_handler_t *handler;
/* RTX SDK vars */
NvVFX_Handle handle;
CUstream stream; // CUDA stream
int mode; // 0 = quality, 1 = performance
NvCVImage *src_img; // src img in obs format (RGBA ?) on GPU
NvCVImage *BGR_src_img; // src img in BGR on GPU
NvCVImage *A_dst_img; // mask img on GPU
NvCVImage *dst_img; // Greenscreen: alpha mask texture; blur: texture initialized from d3d11 (RGBA, chunky, u8)
NvCVImage *stage; // used for transfer to texture
unsigned int version;
NvVFX_StateObjectHandle stateObjectHandle;
/* alpha mask effect */
gs_effect_t *effect;
gs_texrender_t *render;
gs_texrender_t *render_unorm;
gs_texture_t *alpha_texture; // either alpha or blur
uint32_t width; // width of texture
uint32_t height; // height of texture
enum gs_color_space space;
gs_eparam_t *mask_param;
gs_eparam_t *image_param;
gs_eparam_t *threshold_param;
gs_eparam_t *multiplier_param;
float threshold;
/* Every nth frame is processed through the FX (where n =
* processing_interval) so that the same mask is used for n consecutive
* frames. This is to alleviate the GPU load. Default: 1 (process every frame).
* Only used for AIGS.
*/
int processing_interval;
int processing_counter;
/* blur specific */
enum nvvfx_filter_id filter_id;
NvVFX_Handle handle_blur;
CUstream stream_blur; // cuda stream
float strength; // from 0 to 1, default = 0.5
NvCVImage *blur_BGR_dst_img; // dst img of blur FX (BGR, chunky, u8)
NvCVImage *RGBA_dst_img; // tmp img used to transfer to texture
NvCVImage *blur_dst_img; // dst img initialized from d3d11 texture (RGBA, chunky, u8)
gs_texture_t *blur_texture;
gs_eparam_t *blur_param;
};
/* clang-format on */
static const char *nv_greenscreen_filter_name(void *unused)
{
UNUSED_PARAMETER(unused);
return obs_module_text("Nvvfx.Method.Greenscreen");
}
static const char *nv_blur_filter_name(void *unused)
{
UNUSED_PARAMETER(unused);
return obs_module_text("Nvvfx.Method.BlurFilter");
}
static const char *nv_background_blur_filter_name(void *unused)
{
UNUSED_PARAMETER(unused);
return obs_module_text("Nvvfx.Method.BackgroundBlurFilter");
}
static void nvvfx_filter_update(void *data, obs_data_t *settings)
{
struct nvvfx_data *filter = (struct nvvfx_data *)data;
NvCV_Status vfxErr;
enum nvvfx_fx_id id = filter->filter_id;
filter->threshold = (float)obs_data_get_double(settings, S_THRESHOLDFX);
filter->processing_interval = (int)obs_data_get_int(settings, S_PROCESSING);
float strength = (float)obs_data_get_double(settings, S_STRENGTH);
if (id == S_FX_AIGS || id == S_FX_BG_BLUR) {
int mode = id == S_FX_BG_BLUR ? (int)S_MODE_QUALITY : (int)obs_data_get_int(settings, S_MODE);
if (filter->mode != mode) {
filter->mode = mode;
vfxErr = NvVFX_SetU32(filter->handle, NVVFX_MODE, mode);
vfxErr = NvVFX_Load(filter->handle);
if (NVCV_SUCCESS != vfxErr)
error("Error loading AI Greenscreen FX %i", vfxErr);
}
}
if (id == S_FX_BLUR || id == S_FX_BG_BLUR) {
if (filter->strength != strength) {
filter->strength = strength;
vfxErr = NvVFX_SetF32(filter->handle_blur, NVVFX_STRENGTH, filter->strength);
}
vfxErr = NvVFX_Load(filter->handle_blur);
if (NVCV_SUCCESS != vfxErr)
error("Error loading blur FX %i", vfxErr);
}
}
static void nvvfx_filter_actual_destroy(void *data)
{
struct nvvfx_data *filter = (struct nvvfx_data *)data;
if (!nvvfx_loaded) {
bfree(filter);
return;
}
os_atomic_set_bool(&filter->processing_stop, true);
if (filter->images_allocated) {
obs_enter_graphics();
if (filter->filter_id == S_FX_AIGS)
gs_texture_destroy(filter->alpha_texture);
else
gs_texture_destroy(filter->blur_texture);
gs_texrender_destroy(filter->render);
gs_texrender_destroy(filter->render_unorm);
obs_leave_graphics();
NvCVImage_Destroy(filter->src_img);
NvCVImage_Destroy(filter->BGR_src_img);
NvCVImage_Destroy(filter->A_dst_img);
NvCVImage_Destroy(filter->dst_img);
NvCVImage_Destroy(filter->stage);
if (filter->filter_id != S_FX_AIGS) {
NvCVImage_Destroy(filter->blur_BGR_dst_img);
NvCVImage_Destroy(filter->RGBA_dst_img);
NvCVImage_Destroy(filter->blur_dst_img);
}
}
if (filter->stream)
NvVFX_CudaStreamDestroy(filter->stream);
if (filter->stream_blur)
NvVFX_CudaStreamDestroy(filter->stream_blur);
if (filter->handle) {
if (filter->stateObjectHandle) {
NvVFX_DeallocateState(filter->handle, filter->stateObjectHandle);
}
NvVFX_DestroyEffect(filter->handle);
}
if (filter->handle_blur) {
NvVFX_DestroyEffect(filter->handle_blur);
}
if (filter->effect) {
obs_enter_graphics();
gs_effect_destroy(filter->effect);
obs_leave_graphics();
}
bfree(filter);
}
static void nvvfx_filter_destroy(void *data)
{
obs_queue_task(OBS_TASK_GRAPHICS, nvvfx_filter_actual_destroy, data, false);
}
static void *log_nverror_destroy(struct nvvfx_data *filter, NvCV_Status vfxErr)
{
const char *errString = NvCV_GetErrorStringFromCode(vfxErr);
error("Error creating NVIDIA Video FX; error %i: %s", vfxErr, errString);
nvvfx_filter_destroy(filter);
return NULL;
}
//---------------------------------------------------------------------------//
// filter creation //
static bool nvvfx_filter_create_internal(struct nvvfx_data *filter)
{
NvCV_Status vfxErr;
enum nvvfx_fx_id id = filter->filter_id;
/* 1. Create FX */
switch (id) {
case S_FX_AIGS:
vfxErr = NvVFX_CreateEffect(NVVFX_FX_GREEN_SCREEN, &filter->handle);
break;
case S_FX_BLUR:
vfxErr = NvVFX_CreateEffect(NVVFX_FX_BGBLUR, &filter->handle_blur);
break;
case S_FX_BG_BLUR:
vfxErr = NvVFX_CreateEffect(NVVFX_FX_GREEN_SCREEN, &filter->handle);
if (NVCV_SUCCESS != vfxErr)
log_nverror_destroy(filter, vfxErr);
vfxErr = NvVFX_CreateEffect(NVVFX_FX_BGBLUR, &filter->handle_blur);
break;
default:
return false;
}
if (NVCV_SUCCESS != vfxErr)
log_nverror_destroy(filter, vfxErr);
/* debug */
#ifdef _DEBUG
const char *info;
vfxErr = NvVFX_GetString(filter->handle_blur, NVVFX_INFO, &info);
blog(LOG_DEBUG, "blur fx settings /n/%s", info);
#endif
/* 2. Set models path & initialize CudaStream */
if (id == S_FX_AIGS || id == S_FX_BG_BLUR) {
char buffer[MAX_PATH];
char modelDir[MAX_PATH];
nvvfx_get_sdk_path(buffer, MAX_PATH);
size_t max_len = sizeof(buffer) / sizeof(char);
snprintf(modelDir, max_len, "%s\\models", buffer);
vfxErr = NvVFX_SetString(filter->handle, NVVFX_MODEL_DIRECTORY, modelDir);
vfxErr = NvVFX_CudaStreamCreate(&filter->stream);
if (NVCV_SUCCESS != vfxErr)
log_nverror_destroy(filter, vfxErr);
vfxErr = NvVFX_SetCudaStream(filter->handle, NVVFX_CUDA_STREAM, filter->stream);
if (NVCV_SUCCESS != vfxErr)
log_nverror_destroy(filter, vfxErr);
}
if (id == S_FX_BLUR || id == S_FX_BG_BLUR) {
vfxErr = NvVFX_CudaStreamCreate(&filter->stream_blur);
if (NVCV_SUCCESS != vfxErr)
log_nverror_destroy(filter, vfxErr);
vfxErr = NvVFX_SetCudaStream(filter->handle_blur, NVVFX_CUDA_STREAM, filter->stream_blur);
if (NVCV_SUCCESS != vfxErr)
log_nverror_destroy(filter, vfxErr);
}
return true;
}
static void *nvvfx_filter_create(obs_data_t *settings, obs_source_t *context, enum nvvfx_fx_id id)
{
struct nvvfx_data *filter = (struct nvvfx_data *)bzalloc(sizeof(*filter));
if (!nvvfx_loaded) {
nvvfx_filter_destroy(filter);
return NULL;
}
NvCV_Status vfxErr;
filter->context = context;
filter->mode = -1; // should be 0 or 1; -1 triggers an update
filter->images_allocated = false;
filter->processed_frame = true; // start processing when false
filter->width = 0;
filter->height = 0;
filter->initial_render = false;
os_atomic_set_bool(&filter->processing_stop, false);
filter->handler = NULL;
filter->processing_interval = 1;
filter->processing_counter = 0;
// set nvvfx_fx_id
filter->filter_id = id;
// blur specific
filter->strength = -1;
#ifdef _DEBUG
/* sanity check of sdk version */
if (NvVFX_GetVersion(&filter->version) == NVCV_SUCCESS) {
uint8_t major = (filter->version >> 24) & 0xff;
uint8_t minor = (filter->version >> 16) & 0x00ff;
uint8_t build = (filter->version >> 8) & 0x0000ff;
uint8_t revision = (filter->version >> 0) & 0x000000ff;
nvvfx_new_sdk = filter->version >= MIN_VFX_SDK_VERSION && nvvfx_new_sdk;
}
#endif
/* 1. Create FX */
/* 2. Set models path & initialize CudaStream */
if (!nvvfx_filter_create_internal(filter))
return NULL;
/* 3. Load effect. */
char *effect_path = obs_module_file(id != S_FX_AIGS ? "rtx_blur.effect" : "rtx_greenscreen.effect");
obs_enter_graphics();
filter->effect = gs_effect_create_from_file(effect_path, NULL);
bfree(effect_path);
if (filter->effect) {
if (id == S_FX_AIGS) {
filter->mask_param = gs_effect_get_param_by_name(filter->effect, "mask");
filter->threshold_param = gs_effect_get_param_by_name(filter->effect, "threshold");
} else {
filter->blur_param = gs_effect_get_param_by_name(filter->effect, "blurred");
}
filter->image_param = gs_effect_get_param_by_name(filter->effect, "image");
filter->multiplier_param = gs_effect_get_param_by_name(filter->effect, "multiplier");
}
obs_leave_graphics();
/* 4. Allocate state for the AIGS & background blur */
if (nvvfx_new_sdk && id != S_FX_BLUR) {
vfxErr = NvVFX_AllocateState(filter->handle, &filter->stateObjectHandle);
if (NVCV_SUCCESS != vfxErr)
return log_nverror_destroy(filter, vfxErr);
vfxErr = NvVFX_SetStateObjectHandleArray(filter->handle, NVVFX_STATE, &filter->stateObjectHandle);
if (NVCV_SUCCESS != vfxErr)
return log_nverror_destroy(filter, vfxErr);
}
if (!filter->effect) {
nvvfx_filter_destroy(filter);
return NULL;
}
nvvfx_filter_update(filter, settings);
return filter;
}
static void *nv_greenscreen_filter_create(obs_data_t *settings, obs_source_t *context)
{
return nvvfx_filter_create(settings, context, S_FX_AIGS);
}
static void *nv_blur_filter_create(obs_data_t *settings, obs_source_t *context)
{
return nvvfx_filter_create(settings, context, S_FX_BLUR);
}
static void *nv_background_blur_filter_create(obs_data_t *settings, obs_source_t *context)
{
return nvvfx_filter_create(settings, context, S_FX_BG_BLUR);
}
static void nvvfx_filter_reset(void *data, calldata_t *calldata)
{
struct nvvfx_data *filter = (struct nvvfx_data *)data;
NvCV_Status vfxErr;
os_atomic_set_bool(&filter->processing_stop, true);
// [A] first destroy
if (filter->stream) {
NvVFX_CudaStreamDestroy(filter->stream);
}
if (filter->stream_blur) {
NvVFX_CudaStreamDestroy(filter->stream_blur);
}
if (filter->handle) {
if (filter->stateObjectHandle) {
NvVFX_DeallocateState(filter->handle, filter->stateObjectHandle);
}
NvVFX_DestroyEffect(filter->handle);
}
if (filter->handle_blur) {
NvVFX_DestroyEffect(filter->handle_blur);
}
// [B] recreate
/* 1. Create FX */
/* 2. Set models path & initialize CudaStream */
if (!nvvfx_filter_create_internal(filter))
return;
/* 3. load FX */
if (filter->filter_id != S_FX_BLUR) {
vfxErr = NvVFX_SetU32(filter->handle, NVVFX_MODE, filter->mode);
if (NVCV_SUCCESS != vfxErr)
error("Error loading NVIDIA Video FX %i", vfxErr);
vfxErr = NvVFX_Load(filter->handle);
if (NVCV_SUCCESS != vfxErr)
error("Error loading NVIDIA Video FX %i", vfxErr);
vfxErr = NvVFX_ResetState(filter->handle, filter->stateObjectHandle);
}
if (filter->filter_id != S_FX_AIGS) {
vfxErr = NvVFX_SetF32(filter->handle_blur, NVVFX_STRENGTH, filter->strength);
if (NVCV_SUCCESS != vfxErr)
error("Error loading NVIDIA Video FX %i", vfxErr);
vfxErr = NvVFX_Load(filter->handle_blur);
if (NVCV_SUCCESS != vfxErr)
error("Error loading blur FX %i", vfxErr);
}
filter->images_allocated = false;
os_atomic_set_bool(&filter->processing_stop, false);
}
//---------------------------------------------------------------------------//
// intialization of images //
static bool create_alpha_texture(struct nvvfx_data *filter)
{
NvCV_Status vfxErr;
uint32_t width = filter->width;
uint32_t height = filter->height;
/* 1. create alpha texture */
if (filter->alpha_texture) {
gs_texture_destroy(filter->alpha_texture);
}
filter->alpha_texture = gs_texture_create(width, height, GS_A8, 1, NULL, 0);
if (filter->alpha_texture == NULL) {
error("Alpha texture couldn't be created");
return false;
}
struct ID3D11Texture2D *d11texture = (struct ID3D11Texture2D *)gs_texture_get_obj(filter->alpha_texture);
/* 2. Create NvCVImage which will hold final alpha texture. */
if (!filter->dst_img)
NvCVImage_Create(width, height, NVCV_A, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1, &filter->dst_img);
vfxErr = NvCVImage_InitFromD3D11Texture(filter->dst_img, d11texture);
if (vfxErr != NVCV_SUCCESS) {
const char *errString = NvCV_GetErrorStringFromCode(vfxErr);
error("Error passing dst ID3D11Texture to img; error %i: %s", vfxErr, errString);
return false;
}
return true;
}
static bool create_blur_texture(struct nvvfx_data *filter)
{
NvCV_Status vfxErr;
uint32_t width = filter->width;
uint32_t height = filter->height;
/* 1. Create blur texture */
if (filter->blur_texture) {
gs_texture_destroy(filter->blur_texture);
}
filter->blur_texture = gs_texture_create(width, height, GS_RGBA_UNORM, 1, NULL, 0);
if (filter->blur_texture == NULL) {
error("Blur texture couldn't be created");
return false;
}
struct ID3D11Texture2D *d11texture = (struct ID3D11Texture2D *)gs_texture_get_obj(filter->blur_texture);
/* 2. Create NvCVImage which will hold final blur texture */
if (!filter->blur_dst_img)
NvCVImage_Create(width, height, NVCV_RGBA, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1, &filter->blur_dst_img);
vfxErr = NvCVImage_InitFromD3D11Texture(filter->blur_dst_img, d11texture);
if (vfxErr != NVCV_SUCCESS) {
const char *errString = NvCV_GetErrorStringFromCode(vfxErr);
error("Error passing dst ID3D11Texture to img; error %i: %s", vfxErr, errString);
return false;
}
return true;
}
static bool create_texrenders(struct nvvfx_data *filter)
{
if (filter->render)
gs_texrender_destroy(filter->render);
filter->render = gs_texrender_create(gs_get_format_from_space(filter->space), GS_ZS_NONE);
if (!filter->render) {
error("Failed to create render texrenderer");
return false;
}
if (filter->render_unorm)
gs_texrender_destroy(filter->render_unorm);
filter->render_unorm = gs_texrender_create(GS_BGRA_UNORM, GS_ZS_NONE);
if (!filter->render_unorm) {
error("Failed to create render_unorm texrenderer");
return false;
}
return true;
}
static bool init_blur_images(struct nvvfx_data *filter)
{
uint32_t width = filter->width;
uint32_t height = filter->height;
/* 1. Create and allocate Blur BGR NvCVimage (blur FX dst) */
NvCVImage_Create(width, height, NVCV_BGR, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1, &filter->blur_BGR_dst_img);
NvCVImage_Alloc(filter->blur_BGR_dst_img, width, height, NVCV_BGR, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1);
/* 2. Create dst NvCVImage */
if (filter->RGBA_dst_img) {
NvCVImage_Realloc(filter->RGBA_dst_img, width, height, NVCV_RGBA, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1);
} else {
NvCVImage_Create(width, height, NVCV_RGBA, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1, &filter->RGBA_dst_img);
NvCVImage_Alloc(filter->RGBA_dst_img, width, height, NVCV_RGBA, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1);
}
/* 3. Set input & output images for nv blur FX */
NvVFX_SetImage(filter->handle_blur, NVVFX_INPUT_IMAGE, filter->BGR_src_img);
NvVFX_SetImage(filter->handle_blur, NVVFX_INPUT_IMAGE_1, filter->A_dst_img);
NvVFX_SetImage(filter->handle_blur, NVVFX_OUTPUT_IMAGE, filter->blur_BGR_dst_img);
if (NvVFX_Load(filter->handle_blur) != NVCV_SUCCESS) {
error("Error loading blur FX");
return false;
}
return true;
}
static void init_images(struct nvvfx_data *filter)
{
NvCV_Status vfxErr;
uint32_t width = filter->width;
uint32_t height = filter->height;
/* 1. Create alpha texture & associated NvCVImage */
if (filter->filter_id == S_FX_BG_BLUR || filter->filter_id == S_FX_AIGS) {
if (!create_alpha_texture(filter))
goto fail;
}
/* 2. Create blur texture & associated NvCVImage */
if (filter->filter_id == S_FX_BG_BLUR || filter->filter_id == S_FX_BLUR) {
if (!create_blur_texture(filter))
goto fail;
}
/* 3. Create texrenders */
if (!create_texrenders(filter))
goto fail;
/* 4. Create and allocate BGR NvCVImage (alpha mask FX src) */
if (filter->BGR_src_img) {
NvCVImage_Realloc(filter->BGR_src_img, width, height, NVCV_BGR, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1);
} else {
NvCVImage_Create(width, height, NVCV_BGR, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1, &filter->BGR_src_img);
NvCVImage_Alloc(filter->BGR_src_img, width, height, NVCV_BGR, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1);
}
/* 5. Create and allocate Alpha NvCVimage (mask fx dst). */
if (filter->A_dst_img) {
NvCVImage_Realloc(filter->A_dst_img, width, height, NVCV_A, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1);
} else {
NvCVImage_Create(width, height, NVCV_A, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1, &filter->A_dst_img);
NvCVImage_Alloc(filter->A_dst_img, width, height, NVCV_A, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1);
}
/* 6. Create stage NvCVImage which will be used as buffer for transfer */
vfxErr = NvCVImage_Create(width, height, NVCV_RGBA, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1, &filter->stage);
vfxErr = NvCVImage_Alloc(filter->stage, width, height, NVCV_RGBA, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1);
if (vfxErr != NVCV_SUCCESS) {
goto fail;
}
/* 7. Init blur images */
if (filter->filter_id == S_FX_BLUR || filter->filter_id == S_FX_BG_BLUR) {
if (!init_blur_images(filter))
goto fail;
}
/* 8. Pass settings for AIGS (AI Greenscreen) FX */
if (filter->filter_id == S_FX_BG_BLUR || filter->filter_id == S_FX_AIGS) {
NvVFX_SetImage(filter->handle, NVVFX_INPUT_IMAGE, filter->BGR_src_img);
NvVFX_SetImage(filter->handle, NVVFX_OUTPUT_IMAGE, filter->A_dst_img);
if (filter->width)
NvVFX_SetU32(filter->handle, NVVFX_MAX_INPUT_WIDTH, filter->width);
if (filter->height)
NvVFX_SetU32(filter->handle, NVVFX_MAX_INPUT_HEIGHT, filter->height);
vfxErr = NvVFX_Load(filter->handle);
if (NVCV_SUCCESS != vfxErr)
error("Error loading AI Greenscreen FX %i", vfxErr);
}
filter->images_allocated = true;
return;
fail:
error("Error during allocation of images");
os_atomic_set_bool(&filter->processing_stop, true);
return;
}
//---------------------------------------------------------------------------//
// video processing functions //
static bool process_texture(struct nvvfx_data *filter)
{
enum nvvfx_fx_id id = filter->filter_id;
CUstream process_stream;
/* 1. Map src img holding texture. */
switch (id) {
case S_FX_AIGS:
case S_FX_BG_BLUR:
process_stream = filter->stream;
break;
case S_FX_BLUR:
process_stream = filter->stream_blur;
break;
default:
process_stream = NULL;
}
NvCV_Status vfxErr = NvCVImage_MapResource(filter->src_img, process_stream);
if (vfxErr != NVCV_SUCCESS) {
const char *errString = NvCV_GetErrorStringFromCode(vfxErr);
error("Error mapping resource for source texture; error %i : %s", vfxErr, errString);
goto fail;
}
/* 2. Convert to BGR. */
vfxErr = NvCVImage_Transfer(filter->src_img, filter->BGR_src_img, 1.0f, filter->stream_blur, filter->stage);
if (vfxErr != NVCV_SUCCESS) {
const char *errString = NvCV_GetErrorStringFromCode(vfxErr);
error("Error converting src to BGR img; error %i: %s", vfxErr, errString);
goto fail;
}
vfxErr = NvCVImage_UnmapResource(filter->src_img, process_stream);
if (vfxErr != NVCV_SUCCESS) {
const char *errString = NvCV_GetErrorStringFromCode(vfxErr);
error("Error unmapping resource for src texture; error %i: %s", vfxErr, errString);
goto fail;
}
/* 3. Run AIGS (AI Greenscreen) fx */
if (id != S_FX_BLUR) {
vfxErr = NvVFX_Run(filter->handle, 1);
if (vfxErr != NVCV_SUCCESS) {
const char *errString = NvCV_GetErrorStringFromCode(vfxErr);
error("Error running the AIGS FX; error %i: %s", vfxErr, errString);
if (vfxErr == NVCV_ERR_CUDA)
nvvfx_filter_reset(filter, NULL);
}
}
if (id != S_FX_AIGS) {
/* 4. BLUR FX */
/* 4a. Run BLUR FX except for AIGS */
vfxErr = NvVFX_Run(filter->handle_blur, 1);
if (vfxErr != NVCV_SUCCESS) {
const char *errString = NvCV_GetErrorStringFromCode(vfxErr);
error("Error running the BLUR FX; error %i: %s", vfxErr, errString);
if (vfxErr == NVCV_ERR_CUDA)
nvvfx_filter_reset(filter, NULL);
}
/* 4b. Transfer blur result to an intermediate dst [RGBA, chunky, u8] */
vfxErr = NvCVImage_Transfer(filter->blur_BGR_dst_img, filter->RGBA_dst_img, 1.0f, filter->stream_blur,
filter->stage);
if (vfxErr != NVCV_SUCCESS) {
error("Error transferring blurred to intermediate img [RGBA, chunky, u8], error %i, ", vfxErr);
goto fail;
}
/* 5. Map blur dst texture before transfer from dst img provided by FX */
vfxErr = NvCVImage_MapResource(filter->blur_dst_img, filter->stream_blur);
if (vfxErr != NVCV_SUCCESS) {
const char *errString = NvCV_GetErrorStringFromCode(vfxErr);
error("Error mapping resource for dst texture; error %i: %s", vfxErr, errString);
goto fail;
}
vfxErr = NvCVImage_Transfer(filter->RGBA_dst_img, filter->blur_dst_img, 1.0f, filter->stream_blur,
filter->stage);
if (vfxErr != NVCV_SUCCESS) {
const char *errString = NvCV_GetErrorStringFromCode(vfxErr);
error("Error transferring mask to alpha texture; error %i: %s ", vfxErr, errString);
goto fail;
}
vfxErr = NvCVImage_UnmapResource(filter->blur_dst_img, filter->stream_blur);
if (vfxErr != NVCV_SUCCESS) {
const char *errString = NvCV_GetErrorStringFromCode(vfxErr);
error("Error unmapping resource for dst texture; error %i: %s", vfxErr, errString);
goto fail;
}
} else {
/* 4. Map dst texture before transfer from dst img provided by AIGS FX */
vfxErr = NvCVImage_MapResource(filter->dst_img, filter->stream);
if (vfxErr != NVCV_SUCCESS) {
const char *errString = NvCV_GetErrorStringFromCode(vfxErr);
error("Error mapping resource for dst texture; error %i: %s", vfxErr, errString);
goto fail;
}
vfxErr = NvCVImage_Transfer(filter->A_dst_img, filter->dst_img, 1.0f, filter->stream, filter->stage);
if (vfxErr != NVCV_SUCCESS) {
const char *errString = NvCV_GetErrorStringFromCode(vfxErr);
error("Error transferring mask to alpha texture; error %i: %s ", vfxErr, errString);
goto fail;
}
vfxErr = NvCVImage_UnmapResource(filter->dst_img, filter->stream);
if (vfxErr != NVCV_SUCCESS) {
const char *errString = NvCV_GetErrorStringFromCode(vfxErr);
error("Error unmapping resource for dst texture; error %i: %s", vfxErr, errString);
goto fail;
}
}
return true;
fail:
os_atomic_set_bool(&filter->processing_stop, true);
return false;
}
static struct obs_source_frame *nvvfx_filter_video(void *data, struct obs_source_frame *frame)
{
struct nvvfx_data *filter = (struct nvvfx_data *)data;
filter->got_new_frame = true;
return frame;
}
static void nvvfx_filter_tick(void *data, float t)
{
UNUSED_PARAMETER(t);
struct nvvfx_data *filter = (struct nvvfx_data *)data;
if (filter->processing_stop) {
return;
}
if (!obs_filter_get_target(filter->context)) {
return;
}
obs_source_t *target = obs_filter_get_target(filter->context);
filter->target_valid = true;
const uint32_t cx = obs_source_get_base_width(target);
const uint32_t cy = obs_source_get_base_height(target);
// initially the sizes are 0
if (!cx && !cy) {
filter->target_valid = false;
return;
}
/* minimum size supported by SDK is (512,288) */
if (filter->filter_id != S_FX_BLUR) {
filter->target_valid = cx >= 512 && cy >= 288;
if (!filter->target_valid) {
error("Size must be larger than (512,288)");
return;
}
}
if (cx != filter->width && cy != filter->height) {
filter->images_allocated = false;
filter->width = cx;
filter->height = cy;
}
if (!filter->images_allocated) {
obs_enter_graphics();
init_images(filter);
obs_leave_graphics();
filter->initial_render = false;
}
filter->processed_frame = false;
}
static const char *get_tech_name_and_multiplier(enum gs_color_space current_space, enum gs_color_space source_space,
float *multiplier)
{
const char *tech_name = "Draw";
*multiplier = 1.f;
switch (source_space) {
case GS_CS_SRGB:
case GS_CS_SRGB_16F:
if (current_space == GS_CS_709_SCRGB) {
tech_name = "DrawMultiply";
*multiplier = obs_get_video_sdr_white_level() / 80.0f;
}
break;
case GS_CS_709_EXTENDED:
switch (current_space) {
case GS_CS_SRGB:
case GS_CS_SRGB_16F:
tech_name = "DrawTonemap";
break;
case GS_CS_709_SCRGB:
tech_name = "DrawMultiply";
*multiplier = obs_get_video_sdr_white_level() / 80.0f;
}
break;
case GS_CS_709_SCRGB:
switch (current_space) {
case GS_CS_SRGB:
case GS_CS_SRGB_16F:
tech_name = "DrawMultiplyTonemap";
*multiplier = 80.0f / obs_get_video_sdr_white_level();
break;
case GS_CS_709_EXTENDED:
tech_name = "DrawMultiply";
*multiplier = 80.0f / obs_get_video_sdr_white_level();
}
}
return tech_name;
}
static void draw_greenscreen_blur(struct nvvfx_data *filter, bool has_blur)
{
const enum gs_color_space source_space = filter->space;
float multiplier;
const char *technique = get_tech_name_and_multiplier(gs_get_color_space(), source_space, &multiplier);
const enum gs_color_format format = gs_get_format_from_space(source_space);
if (obs_source_process_filter_begin_with_color_space(filter->context, format, source_space,
OBS_ALLOW_DIRECT_RENDERING)) {
if (has_blur) {
gs_effect_set_texture_srgb(filter->blur_param, filter->blur_texture);
} else {
gs_effect_set_texture(filter->mask_param, filter->alpha_texture);
gs_effect_set_float(filter->threshold_param, filter->threshold);
}
gs_effect_set_texture_srgb(filter->image_param, gs_texrender_get_texture(filter->render));
gs_effect_set_float(filter->multiplier_param, multiplier);
gs_blend_state_push();
gs_blend_function(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA);
obs_source_process_filter_tech_end(filter->context, filter->effect, 0, 0, technique);
gs_blend_state_pop();
}
}
static void nvvfx_filter_render(void *data, gs_effect_t *effect, bool has_blur)
{
NvCV_Status vfxErr;
struct nvvfx_data *filter = (struct nvvfx_data *)data;
if (filter->processing_stop || (has_blur && filter->strength == 0)) {
obs_source_skip_video_filter(filter->context);
return;
}
obs_source_t *const target = obs_filter_get_target(filter->context);
obs_source_t *const parent = obs_filter_get_parent(filter->context);
/* Skip if processing of a frame hasn't yet started */
if (!filter->target_valid || !target || !parent) {
obs_source_skip_video_filter(filter->context);
return;
}
/* Render processed image from earlier in the frame */
if (filter->processed_frame) {
draw_greenscreen_blur(filter, has_blur);
return;
}
if (parent && !filter->handler) {
filter->handler = obs_source_get_signal_handler(parent);
signal_handler_connect(filter->handler, "update", nvvfx_filter_reset, filter);
}
/* 1. Render to retrieve texture. */
if (!filter->render) {
obs_source_skip_video_filter(filter->context);
return;
}
const uint32_t target_flags = obs_source_get_output_flags(target);
const uint32_t parent_flags = obs_source_get_output_flags(parent);
bool custom_draw = (target_flags & OBS_SOURCE_CUSTOM_DRAW) != 0;
bool async = (target_flags & OBS_SOURCE_ASYNC) != 0;
const enum gs_color_space preferred_spaces[] = {
GS_CS_SRGB,
GS_CS_SRGB_16F,
GS_CS_709_EXTENDED,
};
const enum gs_color_space source_space =
obs_source_get_color_space(target, OBS_COUNTOF(preferred_spaces), preferred_spaces);
if (filter->space != source_space) {
filter->space = source_space;
init_images(filter);
filter->initial_render = false;
}
gs_texrender_t *const render = filter->render;
gs_texrender_reset(render);
gs_blend_state_push();
gs_blend_function(GS_BLEND_ONE, GS_BLEND_ZERO);
if (gs_texrender_begin_with_color_space(render, filter->width, filter->height, source_space)) {
struct vec4 clear_color;
vec4_zero(&clear_color);
gs_clear(GS_CLEAR_COLOR, &clear_color, 0.0f, 0);
gs_ortho(0.0f, (float)filter->width, 0.0f, (float)filter->height, -100.0f, 100.0f);
if (target == parent && !custom_draw && !async)
obs_source_default_render(target);
else
obs_source_video_render(target);
gs_texrender_end(render);
gs_texrender_t *const render_unorm = filter->render_unorm;
gs_texrender_reset(render_unorm);
if (gs_texrender_begin_with_color_space(render_unorm, filter->width, filter->height, GS_CS_SRGB)) {
const bool previous = gs_framebuffer_srgb_enabled();
gs_enable_framebuffer_srgb(true);
gs_enable_blending(false);
gs_ortho(0.0f, (float)filter->width, 0.0f, (float)filter->height, -100.0f, 100.0f);
const char *tech_name = "ConvertUnorm";
float multiplier = 1.f;
if (!has_blur) {
switch (source_space) {
case GS_CS_709_EXTENDED:
tech_name = "ConvertUnormTonemap";
break;
case GS_CS_709_SCRGB:
tech_name = "ConvertUnormMultiplyTonemap";
multiplier = 80.0f / obs_get_video_sdr_white_level();
}
} else {
switch (source_space) {
case GS_CS_709_SCRGB:
tech_name = "ConvertUnormMultiply";
multiplier = 80.0f / obs_get_video_sdr_white_level();
}
}
gs_effect_set_texture_srgb(filter->image_param, gs_texrender_get_texture(render));
gs_effect_set_float(filter->multiplier_param, multiplier);
while (gs_effect_loop(filter->effect, tech_name)) {
gs_draw(GS_TRIS, 0, 3);
}
gs_texrender_end(render_unorm);
gs_enable_blending(true);
gs_enable_framebuffer_srgb(previous);
}
}
gs_blend_state_pop();
/* 2. Initialize src_texture (only at startup or reset) */
if (!filter->initial_render) {
struct ID3D11Texture2D *d11texture2 =
(struct ID3D11Texture2D *)gs_texture_get_obj(gs_texrender_get_texture(filter->render_unorm));
if (!d11texture2) {
error("Couldn't retrieve d3d11texture2d.");
return;
}
if (!filter->src_img) {
vfxErr = NvCVImage_Create(filter->width, filter->height, NVCV_BGRA, NVCV_U8, NVCV_CHUNKY,
NVCV_GPU, 1, &filter->src_img);
if (vfxErr != NVCV_SUCCESS) {
const char *errString = NvCV_GetErrorStringFromCode(vfxErr);
error("Error creating src img; error %i: %s", vfxErr, errString);
os_atomic_set_bool(&filter->processing_stop, true);
return;
}
}
vfxErr = NvCVImage_InitFromD3D11Texture(filter->src_img, d11texture2);
if (vfxErr != NVCV_SUCCESS) {
const char *errString = NvCV_GetErrorStringFromCode(vfxErr);
error("Error passing src ID3D11Texture to img; error %i: %s", vfxErr, errString);
os_atomic_set_bool(&filter->processing_stop, true);
return;
}
filter->initial_render = true;
}
/* 3. Process FX (outputs a mask) & draw. */
if (filter->initial_render && filter->images_allocated) {
bool draw = true;
if (!async || filter->got_new_frame) {
if (!has_blur) {
if (filter->processing_counter % filter->processing_interval == 0) {
draw = process_texture(filter);
filter->processing_counter = 1;
} else {
filter->processing_counter++;
}
} else {
draw = process_texture(filter);
}
filter->got_new_frame = false;
}
if (draw) {
draw_greenscreen_blur(filter, has_blur);
filter->processed_frame = true;
}
} else {
obs_source_skip_video_filter(filter->context);
}
UNUSED_PARAMETER(effect);
}
static void nv_greenscreen_filter_render(void *data, gs_effect_t *effect)
{
nvvfx_filter_render(data, effect, false);
}
static void nv_blur_filter_render(void *data, gs_effect_t *effect)
{
nvvfx_filter_render(data, effect, true);
}
static enum gs_color_space nvvfx_filter_get_color_space(void *data, size_t count,
const enum gs_color_space *preferred_spaces)
{
const enum gs_color_space potential_spaces[] = {
GS_CS_SRGB,
GS_CS_SRGB_16F,
GS_CS_709_EXTENDED,
};
struct nvvfx_data *const filter = data;
const enum gs_color_space source_space = obs_source_get_color_space(
obs_filter_get_target(filter->context), OBS_COUNTOF(potential_spaces), potential_spaces);
enum gs_color_space space = source_space;
for (size_t i = 0; i < count; ++i) {
space = preferred_spaces[i];
if (space == source_space)
break;
}
return space;
}
static obs_properties_t *nvvfx_filter_properties(void *data)
{
struct nvvfx_data *filter = (struct nvvfx_data *)data;
obs_properties_t *props = obs_properties_create();
if (filter->filter_id != S_FX_AIGS) {
obs_property_t *strength =
obs_properties_add_float_slider(props, S_STRENGTH, TEXT_MODE_BLUR_STRENGTH, 0, 1, 0.05);
} else {
obs_property_t *mode =
obs_properties_add_list(props, S_MODE, TEXT_MODE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
obs_property_list_add_int(mode, TEXT_MODE_QUALITY, S_MODE_QUALITY);
obs_property_list_add_int(mode, TEXT_MODE_PERF, S_MODE_PERF);
obs_property_t *threshold =
obs_properties_add_float_slider(props, S_THRESHOLDFX, TEXT_MODE_THRESHOLD, 0, 1, 0.05);
obs_property_t *partial = obs_properties_add_int_slider(props, S_PROCESSING, TEXT_PROCESSING, 1, 4, 1);
obs_property_set_long_description(partial, TEXT_PROCESSING_HINT);
}
unsigned int version = get_lib_version();
if (version && version < MIN_VFX_SDK_VERSION) {
obs_property_t *warning = obs_properties_add_text(props, "deprecation", NULL, OBS_TEXT_INFO);
obs_property_text_set_info_type(warning, OBS_TEXT_INFO_WARNING);
obs_property_set_long_description(warning, TEXT_DEPRECATION);
}
return props;
}
static void nvvfx_filter_defaults(obs_data_t *settings)
{
obs_data_set_default_int(settings, S_MODE, S_MODE_QUALITY);
obs_data_set_default_double(settings, S_THRESHOLDFX, S_THRESHOLDFX_DEFAULT);
obs_data_set_default_int(settings, S_PROCESSING, 1);
obs_data_set_default_double(settings, S_STRENGTH, S_STRENGTH_DEFAULT);
}
bool load_nvidia_vfx(void)
{
bool old_sdk_loaded = false;
unsigned int version = get_lib_version();
uint8_t major = (version >> 24) & 0xff;
uint8_t minor = (version >> 16) & 0x00ff;
uint8_t build = (version >> 8) & 0x0000ff;
uint8_t revision = (version >> 0) & 0x000000ff;
if (version) {
blog(LOG_INFO, "[NVIDIA VIDEO FX]: NVIDIA VIDEO FX version: %i.%i.%i.%i", major, minor, build,
revision);
if (version < MIN_VFX_SDK_VERSION) {
blog(LOG_INFO,
"[NVIDIA VIDEO FX]: NVIDIA VIDEO Effects SDK is outdated. Please update both audio & video SDK.");
}
}
if (!load_nv_vfx_libs()) {
blog(LOG_INFO, "[NVIDIA VIDEO FX]: FX disabled, redistributable not found or could not be loaded.");
return false;
}
#define LOAD_SYM_FROM_LIB(sym, lib, dll) \
if (!(sym = (sym##_t)GetProcAddress(lib, #sym))) { \
DWORD err = GetLastError(); \
printf("[NVIDIA VIDEO FX]: Couldn't load " #sym " from " dll ": %lu (0x%lx)", err, err); \
release_nv_vfx(); \
goto unload_everything; \
}
#define LOAD_SYM_FROM_LIB2(sym, lib, dll) \
if (!(sym = (sym##_t)GetProcAddress(lib, #sym))) { \
DWORD err = GetLastError(); \
printf("[NVIDIA VIDEO FX]: Couldn't load " #sym " from " dll ": %lu (0x%lx)", err, err); \
nvvfx_new_sdk = false; \
} else { \
nvvfx_new_sdk = true; \
}
#define LOAD_SYM(sym) LOAD_SYM_FROM_LIB(sym, nv_videofx, "NVVideoEffects.dll")
LOAD_SYM(NvVFX_GetVersion);
LOAD_SYM(NvVFX_CreateEffect);
LOAD_SYM(NvVFX_DestroyEffect);
LOAD_SYM(NvVFX_SetU32);
LOAD_SYM(NvVFX_SetS32);
LOAD_SYM(NvVFX_SetF32);
LOAD_SYM(NvVFX_SetF64);
LOAD_SYM(NvVFX_SetU64);
LOAD_SYM(NvVFX_SetObject);
LOAD_SYM(NvVFX_SetCudaStream);
LOAD_SYM(NvVFX_SetImage);
LOAD_SYM(NvVFX_SetString);
LOAD_SYM(NvVFX_GetU32);
LOAD_SYM(NvVFX_GetS32);
LOAD_SYM(NvVFX_GetF32);
LOAD_SYM(NvVFX_GetF64);
LOAD_SYM(NvVFX_GetU64);
LOAD_SYM(NvVFX_GetObject);
LOAD_SYM(NvVFX_GetCudaStream);
LOAD_SYM(NvVFX_GetImage);
LOAD_SYM(NvVFX_GetString);
LOAD_SYM(NvVFX_Run);
LOAD_SYM(NvVFX_Load);
LOAD_SYM(NvVFX_CudaStreamCreate);
LOAD_SYM(NvVFX_CudaStreamDestroy);
old_sdk_loaded = true;
#undef LOAD_SYM
#define LOAD_SYM(sym) LOAD_SYM_FROM_LIB(sym, nv_cvimage, "NVCVImage.dll")
LOAD_SYM(NvCV_GetErrorStringFromCode);
LOAD_SYM(NvCVImage_Init);
LOAD_SYM(NvCVImage_InitView);
LOAD_SYM(NvCVImage_Alloc);
LOAD_SYM(NvCVImage_Realloc);
LOAD_SYM(NvCVImage_Dealloc);
LOAD_SYM(NvCVImage_Create);
LOAD_SYM(NvCVImage_Destroy);
LOAD_SYM(NvCVImage_ComponentOffsets);
LOAD_SYM(NvCVImage_Transfer);
LOAD_SYM(NvCVImage_TransferRect);
LOAD_SYM(NvCVImage_TransferFromYUV);
LOAD_SYM(NvCVImage_TransferToYUV);
LOAD_SYM(NvCVImage_MapResource);
LOAD_SYM(NvCVImage_UnmapResource);
LOAD_SYM(NvCVImage_Composite);
LOAD_SYM(NvCVImage_CompositeRect);
LOAD_SYM(NvCVImage_CompositeOverConstant);
LOAD_SYM(NvCVImage_FlipY);
LOAD_SYM(NvCVImage_GetYUVPointers);
LOAD_SYM(NvCVImage_InitFromD3D11Texture);
LOAD_SYM(NvCVImage_ToD3DFormat);
LOAD_SYM(NvCVImage_FromD3DFormat);
LOAD_SYM(NvCVImage_ToD3DColorSpace);
LOAD_SYM(NvCVImage_FromD3DColorSpace);
#undef LOAD_SYM
#define LOAD_SYM(sym) LOAD_SYM_FROM_LIB(sym, nv_cudart, "cudart64_110.dll")
LOAD_SYM(cudaMalloc);
LOAD_SYM(cudaStreamSynchronize);
LOAD_SYM(cudaFree);
LOAD_SYM(cudaMemcpy);
LOAD_SYM(cudaMemsetAsync);
#undef LOAD_SYM
#define LOAD_SYM(sym) LOAD_SYM_FROM_LIB2(sym, nv_videofx, "NVVideoEffects.dll")
LOAD_SYM(NvVFX_SetStateObjectHandleArray);
LOAD_SYM(NvVFX_AllocateState);
LOAD_SYM(NvVFX_DeallocateState);
LOAD_SYM(NvVFX_ResetState);
if (!nvvfx_new_sdk) {
blog(LOG_INFO, "[NVIDIA VIDEO FX]: sdk loaded but old redistributable detected; please upgrade.");
}
#undef LOAD_SYM
int err;
NvVFX_Handle h = NULL;
/* load the effect to check if the GPU is supported */
err = NvVFX_CreateEffect(NVVFX_FX_GREEN_SCREEN, &h);
if (err != NVCV_SUCCESS) {
if (err == NVCV_ERR_UNSUPPORTEDGPU) {
blog(LOG_INFO, "[NVIDIA VIDEO FX]: disabled, unsupported GPU");
} else {
blog(LOG_ERROR, "[NVIDIA VIDEO FX]: disabled, error %i", err);
}
goto unload_everything;
}
NvVFX_DestroyEffect(h);
nvvfx_loaded = true;
blog(LOG_INFO, "[NVIDIA VIDEO FX]: enabled, redistributable found");
return true;
unload_everything:
nvvfx_loaded = false;
blog(LOG_INFO, "[NVIDIA VIDEO FX]: disabled, redistributable not found");
release_nv_vfx();
return false;
}
void unload_nvidia_vfx(void)
{
release_nv_vfx();
}
struct obs_source_info nvidia_greenscreen_filter_info = {
.id = "nv_greenscreen_filter",
.type = OBS_SOURCE_TYPE_FILTER,
.output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_SRGB,
.get_name = nv_greenscreen_filter_name,
.create = nv_greenscreen_filter_create,
.destroy = nvvfx_filter_destroy,
.get_defaults = nvvfx_filter_defaults,
.get_properties = nvvfx_filter_properties,
.update = nvvfx_filter_update,
.filter_video = nvvfx_filter_video,
.video_render = nv_greenscreen_filter_render,
.video_tick = nvvfx_filter_tick,
.video_get_color_space = nvvfx_filter_get_color_space,
};
struct obs_source_info nvidia_blur_filter_info = {
.id = "nv_blur_filter",
.type = OBS_SOURCE_TYPE_FILTER,
.output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_SRGB,
.get_name = nv_blur_filter_name,
.create = nv_blur_filter_create,
.destroy = nvvfx_filter_destroy,
.get_defaults = nvvfx_filter_defaults,
.get_properties = nvvfx_filter_properties,
.update = nvvfx_filter_update,
.filter_video = nvvfx_filter_video,
.video_render = nv_blur_filter_render,
.video_tick = nvvfx_filter_tick,
.video_get_color_space = nvvfx_filter_get_color_space,
};
struct obs_source_info nvidia_background_blur_filter_info = {
.id = "nv_background_blur_filter",
.type = OBS_SOURCE_TYPE_FILTER,
.output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_SRGB,
.get_name = nv_background_blur_filter_name,
.create = nv_background_blur_filter_create,
.destroy = nvvfx_filter_destroy,
.get_defaults = nvvfx_filter_defaults,
.get_properties = nvvfx_filter_properties,
.update = nvvfx_filter_update,
.filter_video = nvvfx_filter_video,
.video_render = nv_blur_filter_render,
.video_tick = nvvfx_filter_tick,
.video_get_color_space = nvvfx_filter_get_color_space,
};
| 42,595 |
C
|
.c
| 1,135 | 34.939207 | 120 | 0.697524 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,358 |
audio-repack.c
|
obsproject_obs-studio/plugins/aja/audio-repack.c
|
#include "audio-repack.h"
#define USE_SIMD
#ifdef USE_SIMD
#include <util/sse-intrin.h>
#endif
#define NUM_CHANNELS 8 /* max until OBS supports higher channel counts */
int check_buffer(struct audio_repack *repack, uint32_t frame_count)
{
const uint32_t new_size = frame_count * repack->base_dst_size + repack->pad_dst_size;
if (repack->packet_size < new_size) {
repack->packet_buffer = brealloc(repack->packet_buffer, new_size);
if (!repack->packet_buffer)
return -1;
repack->packet_size = new_size;
}
return 0;
}
#ifdef USE_SIMD
/*
* Squash array of 8ch to new channel count
* 16-bit PCM, SIMD version
* For instance:
* 2.1:
*
* | FL | FR | LFE | emp | emp | emp |emp |emp |
* | | |
* | FL | FR | LFE |
*/
int repack_squash16(struct audio_repack *repack, const uint8_t *bsrc, uint32_t frame_count)
{
if (check_buffer(repack, frame_count) < 0)
return -1;
int squash = repack->squash_count;
const __m128i *src = (__m128i *)bsrc;
const __m128i *end = src + frame_count;
uint16_t *dst = (uint16_t *)repack->packet_buffer;
/* Audio needs squashing in order to avoid resampling issues.
* The condition checks for 7.1 audio for which no squash is needed.
*/
if (squash > 0) {
while (src != end) {
__m128i target = _mm_load_si128(src++);
_mm_storeu_si128((__m128i *)dst, target);
dst += NUM_CHANNELS - squash;
}
}
return 0;
}
/*
* Squash array of 8ch and swap Front Center channel with LFE
* 16-bit PCM, SIMD version
* For instance:
* 2.1:
*
* | FL | FR | FC | LFE | RL | RR | LC | RC |
* | | |
* | FL | FR | LFE | FC | RL | RR | LC | RC |
*/
int repack_squash_swap16(struct audio_repack *repack, const uint8_t *bsrc, uint32_t frame_count)
{
if (check_buffer(repack, frame_count) < 0)
return -1;
int squash = repack->squash_count;
const __m128i *src = (__m128i *)bsrc;
const __m128i *end = src + frame_count;
uint16_t *dst = (uint16_t *)repack->packet_buffer;
while (src != end) {
__m128i target = _mm_load_si128(src++);
__m128i buf = _mm_shufflelo_epi16(target, _MM_SHUFFLE(2, 3, 1, 0));
_mm_storeu_si128((__m128i *)dst, buf);
dst += NUM_CHANNELS - squash;
}
return 0;
}
/*
* Squash array of 8ch to new channel count
* 32-bit PCM, SIMD version
*/
int repack_squash32(struct audio_repack *repack, const uint8_t *bsrc, uint32_t frame_count)
{
if (check_buffer(repack, frame_count) < 0)
return -1;
int squash = repack->squash_count;
const __m128i *src = (__m128i *)bsrc;
const __m128i *end = (__m128i *)(bsrc + (frame_count * repack->base_src_size));
uint32_t *dst = (uint32_t *)repack->packet_buffer;
if (squash > 0) {
while (src != end) {
__m128i tgt_lo = _mm_loadu_si128(src++);
__m128i tgt_hi = _mm_loadu_si128(src++);
_mm_storeu_si128((__m128i *)dst, tgt_lo);
dst += 4;
_mm_storeu_si128((__m128i *)dst, tgt_hi);
dst += 4;
dst -= squash;
}
}
return 0;
}
/*
* Squash array of 8ch to new channel count and swap FC with LFE
* 32-bit PCM, SIMD version
*/
int repack_squash_swap32(struct audio_repack *repack, const uint8_t *bsrc, uint32_t frame_count)
{
if (check_buffer(repack, frame_count) < 0)
return -1;
int squash = repack->squash_count;
const __m128i *src = (__m128i *)bsrc;
const __m128i *end = (__m128i *)(bsrc + (frame_count * repack->base_src_size));
uint32_t *dst = (uint32_t *)repack->packet_buffer;
while (src != end) {
__m128i tgt_lo = _mm_shuffle_epi32(_mm_loadu_si128(src++), _MM_SHUFFLE(2, 3, 1, 0));
__m128i tgt_hi = _mm_loadu_si128(src++);
_mm_storeu_si128((__m128i *)dst, tgt_lo);
dst += 4;
_mm_storeu_si128((__m128i *)dst, tgt_hi);
dst += 4;
dst -= squash;
}
return 0;
}
#else
/*
* Squash array of 8ch to new channel count
* 16-bit or 32-bit PCM, C version
*/
int repack_squash(struct audio_repack *repack, const uint8_t *bsrc, uint32_t frame_count)
{
if (check_buffer(repack, frame_count) < 0)
return -1;
int squash = repack->squash_count;
const uint8_t *src = bsrc;
const uint8_t *end = src + frame_count * repack->base_src_size;
uint8_t *dst = repack->packet_buffer;
uint32_t new_channel_count = NUM_CHANNELS - squash;
if (squash > 0) {
while (src != end) {
memcpy(dst, src, repack->bytes_per_sample * new_channel_count);
dst += (new_channel_count * repack->bytes_per_sample);
src += NUM_CHANNELS * repack->bytes_per_sample;
}
}
return 0;
}
void shuffle_8ch(uint8_t *dst, const uint8_t *src, size_t szb, int ch1, int ch2, int ch3, int ch4, int ch5, int ch6,
int ch7, int ch8)
{
/* shuffle 8 channels of audio */
for (size_t i = 0; i < szb; i++) {
dst[0 * szb + i] = src[ch1 * szb + i];
dst[1 * szb + i] = src[ch2 * szb + i];
dst[2 * szb + i] = src[ch3 * szb + i];
dst[3 * szb + i] = src[ch4 * szb + i];
dst[4 * szb + i] = src[ch5 * szb + i];
dst[5 * szb + i] = src[ch6 * szb + i];
dst[6 * szb + i] = src[ch7 * szb + i];
dst[7 * szb + i] = src[ch8 * szb + i];
}
}
/*
* Squash array of 8ch to new channel count and swap FC with LFE
* 16-bit or 32-bit PCM, C version
*/
int repack_squash_swap(struct audio_repack *repack, const uint8_t *bsrc, uint32_t frame_count)
{
if (check_buffer(repack, frame_count) < 0)
return -1;
int squash = repack->squash_count;
const uint8_t *src = bsrc;
const uint8_t *end = src + (frame_count * repack->base_src_size);
uint8_t *dst = repack->packet_buffer;
uint32_t new_channel_count = NUM_CHANNELS - squash;
if (squash > 0) {
while (src != end) {
shuffle_8ch(dst, src, 4, 0, 1, 3, 2, 4, 5, 6, 7);
dst += (new_channel_count * repack->bytes_per_sample);
src += (NUM_CHANNELS * repack->bytes_per_sample);
}
}
return 0;
}
#endif
int audio_repack_init(struct audio_repack *repack, audio_repack_mode_t repack_mode, uint8_t bits_per_sample)
{
memset(repack, 0, sizeof(*repack));
if (bits_per_sample != 16 && bits_per_sample != 32)
return -1;
int _audio_repack_ch[9] = {2, 3, 4, 5, 6, 5, 6, 8, 8};
int bytes_per_sample = (bits_per_sample / 8);
repack->bytes_per_sample = bytes_per_sample;
repack->base_src_size = NUM_CHANNELS * bytes_per_sample;
repack->base_dst_size = _audio_repack_ch[repack_mode] * bytes_per_sample;
uint32_t squash_count = NUM_CHANNELS - _audio_repack_ch[repack_mode];
repack->pad_dst_size = squash_count * bytes_per_sample;
repack->squash_count = squash_count;
#ifdef USE_SIMD
if (bits_per_sample == 16) {
repack->repack_func = &repack_squash16;
if (repack_mode == repack_mode_8to5ch_swap || repack_mode == repack_mode_8to6ch_swap ||
repack_mode == repack_mode_8ch_swap)
repack->repack_func = &repack_squash_swap16;
} else if (bits_per_sample == 32) {
repack->repack_func = &repack_squash32;
if (repack_mode == repack_mode_8to5ch_swap || repack_mode == repack_mode_8to6ch_swap ||
repack_mode == repack_mode_8ch_swap)
repack->repack_func = &repack_squash_swap32;
}
#else
repack->repack_func = &repack_squash;
if (repack_mode == repack_mode_8to5ch_swap || repack_mode == repack_mode_8to6ch_swap ||
repack_mode == repack_mode_8ch_swap)
repack->repack_func = &repack_squash_swap;
#endif
return 0;
}
void audio_repack_free(struct audio_repack *repack)
{
if (repack->packet_buffer)
bfree(repack->packet_buffer);
memset(repack, 0, sizeof(*repack));
}
| 7,214 |
C
|
.c
| 222 | 30.148649 | 116 | 0.657381 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,385 |
hdr-tonemap-filter.c
|
obsproject_obs-studio/plugins/obs-filters/hdr-tonemap-filter.c
|
#include <obs-module.h>
enum hdr_tonemap_transform {
TRANSFORM_SDR_REINHARD,
TRANSFORM_HDR_MAXRGB,
TRANSFORM_SDR_MAXRGB,
};
struct hdr_tonemap_filter_data {
obs_source_t *context;
gs_effect_t *effect;
gs_eparam_t *param_multiplier;
gs_eparam_t *param_input_maximum_nits;
gs_eparam_t *param_output_maximum_nits;
enum hdr_tonemap_transform transform;
float sdr_white_level_nits_i;
float hdr_input_maximum_nits;
float hdr_output_maximum_nits;
float sdr_input_maximum_nits;
float sdr_output_maximum_nits;
};
static const char *hdr_tonemap_filter_get_name(void *unused)
{
UNUSED_PARAMETER(unused);
return obs_module_text("HdrTonemapFilter");
}
static void *hdr_tonemap_filter_create(obs_data_t *settings, obs_source_t *context)
{
struct hdr_tonemap_filter_data *filter = bzalloc(sizeof(*filter));
char *effect_path = obs_module_file("hdr_tonemap_filter.effect");
filter->context = context;
obs_enter_graphics();
filter->effect = gs_effect_create_from_file(effect_path, NULL);
obs_leave_graphics();
bfree(effect_path);
if (!filter->effect) {
bfree(filter);
return NULL;
}
filter->param_multiplier = gs_effect_get_param_by_name(filter->effect, "multiplier");
filter->param_input_maximum_nits = gs_effect_get_param_by_name(filter->effect, "input_maximum_nits");
filter->param_output_maximum_nits = gs_effect_get_param_by_name(filter->effect, "output_maximum_nits");
obs_source_update(context, settings);
return filter;
}
static void hdr_tonemap_filter_destroy(void *data)
{
struct hdr_tonemap_filter_data *filter = data;
obs_enter_graphics();
gs_effect_destroy(filter->effect);
obs_leave_graphics();
bfree(filter);
}
static void hdr_tonemap_filter_update(void *data, obs_data_t *settings)
{
struct hdr_tonemap_filter_data *filter = data;
filter->transform = obs_data_get_int(settings, "transform");
filter->sdr_white_level_nits_i = 1.f / (float)obs_data_get_int(settings, "sdr_white_level_nits");
filter->hdr_input_maximum_nits = (float)obs_data_get_int(settings, "hdr_input_maximum_nits");
filter->hdr_output_maximum_nits = (float)obs_data_get_int(settings, "hdr_output_maximum_nits");
filter->sdr_input_maximum_nits = (float)obs_data_get_int(settings, "sdr_input_maximum_nits");
filter->sdr_output_maximum_nits = (float)obs_data_get_int(settings, "sdr_output_maximum_nits");
}
static bool transform_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *settings)
{
enum hdr_tonemap_transform transform = obs_data_get_int(settings, "transform");
const bool reinhard = transform == TRANSFORM_SDR_REINHARD;
const bool maxrgb_hdr = transform == TRANSFORM_HDR_MAXRGB;
const bool maxrgb_sdr = transform == TRANSFORM_SDR_MAXRGB;
obs_property_set_visible(obs_properties_get(props, "sdr_white_level_nits"), reinhard);
obs_property_set_visible(obs_properties_get(props, "hdr_input_maximum_nits"), maxrgb_hdr);
obs_property_set_visible(obs_properties_get(props, "hdr_output_maximum_nits"), maxrgb_hdr);
obs_property_set_visible(obs_properties_get(props, "sdr_input_maximum_nits"), maxrgb_sdr);
obs_property_set_visible(obs_properties_get(props, "sdr_output_maximum_nits"), maxrgb_sdr);
UNUSED_PARAMETER(p);
return true;
}
static obs_properties_t *hdr_tonemap_filter_properties(void *data)
{
obs_properties_t *props = obs_properties_create();
obs_properties_add_text(props, "override_info", obs_module_text("HdrTonemap.Description"), OBS_TEXT_INFO);
obs_property_t *p = obs_properties_add_list(props, "transform", obs_module_text("HdrTonemap.ToneTransform"),
OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
obs_property_list_add_int(p, obs_module_text("HdrTonemap.SdrReinhard"), TRANSFORM_SDR_REINHARD);
obs_property_list_add_int(p, obs_module_text("HdrTonemap.HdrMaxrgb"), TRANSFORM_HDR_MAXRGB);
obs_property_list_add_int(p, obs_module_text("HdrTonemap.SdrMaxrgb"), TRANSFORM_SDR_MAXRGB);
obs_property_set_modified_callback(p, transform_changed);
p = obs_properties_add_int(props, "sdr_white_level_nits", obs_module_text("HdrTonemap.SdrWhiteLevel"), 80, 480,
1);
obs_property_int_set_suffix(p, " nits");
p = obs_properties_add_int(props, "hdr_input_maximum_nits", obs_module_text("HdrTonemap.HdrInputMaximum"), 5,
10000, 1);
obs_property_int_set_suffix(p, " nits");
p = obs_properties_add_int(props, "hdr_output_maximum_nits", obs_module_text("HdrTonemap.HdrOutputMaximum"), 5,
10000, 1);
obs_property_int_set_suffix(p, " nits");
p = obs_properties_add_int(props, "sdr_input_maximum_nits", obs_module_text("HdrTonemap.SdrInputMaximum"), 5,
10000, 1);
obs_property_int_set_suffix(p, " nits");
p = obs_properties_add_int(props, "sdr_output_maximum_nits", obs_module_text("HdrTonemap.SdrOutputMaximum"), 5,
10000, 1);
obs_property_int_set_suffix(p, " nits");
UNUSED_PARAMETER(data);
return props;
}
static void hdr_tonemap_filter_defaults(obs_data_t *settings)
{
obs_data_set_default_int(settings, "transform", TRANSFORM_SDR_REINHARD);
obs_data_set_default_int(settings, "sdr_white_level_nits", 300);
obs_data_set_default_int(settings, "hdr_input_maximum_nits", 4000);
obs_data_set_default_int(settings, "hdr_output_maximum_nits", 1000);
obs_data_set_default_int(settings, "sdr_input_maximum_nits", 1000);
obs_data_set_default_int(settings, "sdr_output_maximum_nits", 300);
}
static void hdr_tonemap_filter_render(void *data, gs_effect_t *effect)
{
UNUSED_PARAMETER(effect);
struct hdr_tonemap_filter_data *filter = data;
const enum gs_color_space preferred_spaces[] = {
GS_CS_SRGB,
GS_CS_SRGB_16F,
GS_CS_709_EXTENDED,
};
enum gs_color_space source_space = obs_source_get_color_space(obs_filter_get_target(filter->context),
OBS_COUNTOF(preferred_spaces), preferred_spaces);
switch (source_space) {
case GS_CS_709_EXTENDED:
case GS_CS_709_SCRGB: {
float multiplier = (source_space == GS_CS_709_EXTENDED) ? obs_get_video_sdr_white_level() : 80.f;
multiplier *= (filter->transform == TRANSFORM_SDR_REINHARD) ? filter->sdr_white_level_nits_i : 0.0001f;
const enum gs_color_format format = gs_get_format_from_space(source_space);
if (obs_source_process_filter_begin_with_color_space(filter->context, format, source_space,
OBS_NO_DIRECT_RENDERING)) {
gs_effect_set_float(filter->param_multiplier, multiplier);
gs_effect_set_float(filter->param_input_maximum_nits,
(filter->transform == TRANSFORM_SDR_MAXRGB)
? filter->sdr_input_maximum_nits
: filter->hdr_input_maximum_nits);
gs_effect_set_float(filter->param_output_maximum_nits,
(filter->transform == TRANSFORM_SDR_MAXRGB)
? filter->sdr_output_maximum_nits
: filter->hdr_output_maximum_nits);
gs_blend_state_push();
gs_blend_function(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA);
const char *const tech_name =
(filter->transform == TRANSFORM_SDR_REINHARD)
? "Reinhard"
: ((filter->transform == TRANSFORM_HDR_MAXRGB) ? "MaxRGB" : "MaxRGBSDR");
obs_source_process_filter_tech_end(filter->context, filter->effect, 0, 0, tech_name);
gs_blend_state_pop();
}
break;
}
default:
obs_source_skip_video_filter(filter->context);
}
}
static enum gs_color_space hdr_tonemap_filter_get_color_space(void *data, size_t count,
const enum gs_color_space *preferred_spaces)
{
const enum gs_color_space potential_spaces[] = {
GS_CS_SRGB,
GS_CS_SRGB_16F,
GS_CS_709_EXTENDED,
};
struct hdr_tonemap_filter_data *const filter = data;
const enum gs_color_space source_space = obs_source_get_color_space(
obs_filter_get_target(filter->context), OBS_COUNTOF(potential_spaces), potential_spaces);
enum gs_color_space space = source_space;
if (source_space == GS_CS_709_EXTENDED || source_space == GS_CS_SRGB) {
if ((filter->transform == TRANSFORM_SDR_REINHARD) || filter->transform == TRANSFORM_SDR_MAXRGB) {
space = GS_CS_SRGB;
for (size_t i = 0; i < count; ++i) {
if (preferred_spaces[i] != GS_CS_SRGB) {
space = GS_CS_SRGB_16F;
break;
}
}
}
}
return space;
}
struct obs_source_info hdr_tonemap_filter = {
.id = "hdr_tonemap_filter",
.type = OBS_SOURCE_TYPE_FILTER,
.output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_SRGB,
.get_name = hdr_tonemap_filter_get_name,
.create = hdr_tonemap_filter_create,
.destroy = hdr_tonemap_filter_destroy,
.update = hdr_tonemap_filter_update,
.get_properties = hdr_tonemap_filter_properties,
.get_defaults = hdr_tonemap_filter_defaults,
.video_render = hdr_tonemap_filter_render,
.video_get_color_space = hdr_tonemap_filter_get_color_space,
};
| 8,562 |
C
|
.c
| 193 | 41.331606 | 112 | 0.732621 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,388 |
eq-filter.c
|
obsproject_obs-studio/plugins/obs-filters/eq-filter.c
|
#include <media-io/audio-math.h>
#include <util/deque.h>
#include <util/darray.h>
#include <obs-module.h>
#include <math.h>
#define LOW_FREQ 800.0f
#define HIGH_FREQ 5000.0f
struct eq_channel_state {
float lf_delay0;
float lf_delay1;
float lf_delay2;
float lf_delay3;
float hf_delay0;
float hf_delay1;
float hf_delay2;
float hf_delay3;
float sample_delay1;
float sample_delay2;
float sample_delay3;
};
struct eq_data {
obs_source_t *context;
size_t channels;
struct eq_channel_state eqs[MAX_AUDIO_CHANNELS];
float lf;
float hf;
float low_gain;
float mid_gain;
float high_gain;
};
static const char *eq_name(void *unused)
{
UNUSED_PARAMETER(unused);
return obs_module_text("3BandEq");
}
static void eq_update(void *data, obs_data_t *settings)
{
struct eq_data *eq = data;
eq->low_gain = db_to_mul((float)obs_data_get_double(settings, "low"));
eq->mid_gain = db_to_mul((float)obs_data_get_double(settings, "mid"));
eq->high_gain = db_to_mul((float)obs_data_get_double(settings, "high"));
}
static void eq_defaults(obs_data_t *defaults)
{
obs_data_set_default_double(defaults, "low", 0.0);
obs_data_set_default_double(defaults, "mid", 0.0);
obs_data_set_default_double(defaults, "high", 0.0);
}
static obs_properties_t *eq_properties(void *unused)
{
obs_properties_t *props = obs_properties_create();
obs_property_t *p;
#define make_db_slider(name) \
p = obs_properties_add_float_slider(props, name, obs_module_text("3BandEq." name), -20.0f, 20.0, 0.1); \
obs_property_float_set_suffix(p, " dB");
make_db_slider("high");
make_db_slider("mid");
make_db_slider("low");
#undef make_db_slider
UNUSED_PARAMETER(unused);
return props;
}
static void *eq_create(obs_data_t *settings, obs_source_t *filter)
{
struct eq_data *eq = bzalloc(sizeof(*eq));
eq->channels = audio_output_get_channels(obs_get_audio());
eq->context = filter;
float freq = (float)audio_output_get_sample_rate(obs_get_audio());
eq->lf = 2.0f * sinf(M_PI * LOW_FREQ / freq);
eq->hf = 2.0f * sinf(M_PI * HIGH_FREQ / freq);
eq_update(eq, settings);
return eq;
}
static void eq_destroy(void *data)
{
struct eq_data *eq = data;
bfree(eq);
}
#define EQ_EPSILON (1.0f / 4294967295.0f)
static inline float eq_process(struct eq_data *eq, struct eq_channel_state *c, float sample)
{
float l, m, h;
c->lf_delay0 += eq->lf * (sample - c->lf_delay0) + EQ_EPSILON;
c->lf_delay1 += eq->lf * (c->lf_delay0 - c->lf_delay1);
c->lf_delay2 += eq->lf * (c->lf_delay1 - c->lf_delay2);
c->lf_delay3 += eq->lf * (c->lf_delay2 - c->lf_delay3);
l = c->lf_delay3;
c->hf_delay0 += eq->hf * (sample - c->hf_delay0) + EQ_EPSILON;
c->hf_delay1 += eq->hf * (c->hf_delay0 - c->hf_delay1);
c->hf_delay2 += eq->hf * (c->hf_delay1 - c->hf_delay2);
c->hf_delay3 += eq->hf * (c->hf_delay2 - c->hf_delay3);
h = c->sample_delay3 - c->hf_delay3;
m = c->sample_delay3 - (h + l);
l *= eq->low_gain;
m *= eq->mid_gain;
h *= eq->high_gain;
c->sample_delay3 = c->sample_delay2;
c->sample_delay2 = c->sample_delay1;
c->sample_delay1 = sample;
return l + m + h;
}
static struct obs_audio_data *eq_filter_audio(void *data, struct obs_audio_data *audio)
{
struct eq_data *eq = data;
const uint32_t frames = audio->frames;
for (size_t c = 0; c < eq->channels; c++) {
float *adata = (float *)audio->data[c];
struct eq_channel_state *channel = &eq->eqs[c];
for (size_t i = 0; i < frames; i++) {
adata[i] = eq_process(eq, channel, adata[i]);
}
}
return audio;
}
struct obs_source_info eq_filter = {
.id = "basic_eq_filter",
.type = OBS_SOURCE_TYPE_FILTER,
.output_flags = OBS_SOURCE_AUDIO,
.get_name = eq_name,
.create = eq_create,
.destroy = eq_destroy,
.update = eq_update,
.filter_audio = eq_filter_audio,
.get_defaults = eq_defaults,
.get_properties = eq_properties,
};
| 3,885 |
C
|
.c
| 126 | 28.857143 | 112 | 0.666845 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,390 |
noise-suppress-filter.c
|
obsproject_obs-studio/plugins/obs-filters/noise-suppress-filter.c
|
#include <stdint.h>
#include <inttypes.h>
#include <util/deque.h>
#include <util/threading.h>
#include <obs-module.h>
#ifdef LIBSPEEXDSP_ENABLED
#include <speex/speex_preprocess.h>
#endif
#ifdef LIBRNNOISE_ENABLED
#ifdef _MSC_VER
#define ssize_t intptr_t
#endif
#include <rnnoise.h>
#include <media-io/audio-resampler.h>
#endif
bool nvafx_loaded = false;
#ifdef LIBNVAFX_ENABLED
#include "nvafx-load.h"
#include <pthread.h>
#endif
/* -------------------------------------------------------- */
#define do_log(level, format, ...) \
blog(level, "[noise suppress: '%s'] " format, obs_source_get_name(ng->context), ##__VA_ARGS__)
#define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
#define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
#ifdef _DEBUG
#define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
#else
#define debug(format, ...)
#endif
/* -------------------------------------------------------- */
#define S_SUPPRESS_LEVEL "suppress_level"
#define S_NVAFX_INTENSITY "intensity"
#define S_METHOD "method"
#define S_METHOD_SPEEX "speex"
#define S_METHOD_RNN "rnnoise"
#define S_METHOD_NVAFX_DENOISER "denoiser"
#define S_METHOD_NVAFX_DEREVERB "dereverb"
#define S_METHOD_NVAFX_DEREVERB_DENOISER "dereverb_denoiser"
#define MT_ obs_module_text
#define TEXT_SUPPRESS_LEVEL MT_("NoiseSuppress.SuppressLevel")
#define TEXT_NVAFX_INTENSITY MT_("NoiseSuppress.Intensity")
#define TEXT_METHOD MT_("NoiseSuppress.Method")
#define TEXT_METHOD_SPEEX MT_("NoiseSuppress.Method.Speex")
#define TEXT_METHOD_RNN MT_("NoiseSuppress.Method.RNNoise")
#define TEXT_METHOD_NVAFX_DENOISER MT_("NoiseSuppress.Method.Nvafx.Denoiser")
#define TEXT_METHOD_NVAFX_DEREVERB MT_("NoiseSuppress.Method.Nvafx.Dereverb")
#define TEXT_METHOD_NVAFX_DEREVERB_DENOISER MT_("NoiseSuppress.Method.Nvafx.DenoiserPlusDereverb")
#define TEXT_METHOD_NVAFX_DEPRECATION MT_("NoiseSuppress.Method.Nvafx.Deprecation")
#define TEXT_METHOD_NVAFX_DEPRECATION2 MT_("NoiseSuppress.Method.Nvafx.Deprecation2")
#define MAX_PREPROC_CHANNELS 8
/* RNNoise constants, these can't be changed */
#define RNNOISE_SAMPLE_RATE 48000
#define RNNOISE_FRAME_SIZE 480
/* nvafx constants, these can't be changed */
#define NVAFX_SAMPLE_RATE 48000
#define NVAFX_FRAME_SIZE 480 /* the sdk does not explicitly set this as a constant though it relies on it*/
/* If the following constant changes, RNNoise breaks */
#define BUFFER_SIZE_MSEC 10
/* -------------------------------------------------------- */
struct noise_suppress_data {
obs_source_t *context;
int suppress_level;
uint64_t last_timestamp;
uint64_t latency;
size_t frames;
size_t channels;
struct deque info_buffer;
struct deque input_buffers[MAX_PREPROC_CHANNELS];
struct deque output_buffers[MAX_PREPROC_CHANNELS];
bool use_rnnoise;
bool nvafx_enabled;
bool nvafx_migrated;
#ifdef LIBNVAFX_ENABLED
obs_source_t *migrated_filter;
#endif
bool has_mono_src;
volatile bool reinit_done;
#ifdef LIBSPEEXDSP_ENABLED
/* Speex preprocessor state */
SpeexPreprocessState *spx_states[MAX_PREPROC_CHANNELS];
#endif
#ifdef LIBRNNOISE_ENABLED
/* RNNoise state */
DenoiseState *rnn_states[MAX_PREPROC_CHANNELS];
/* Resampler */
audio_resampler_t *rnn_resampler;
audio_resampler_t *rnn_resampler_back;
#endif
/* PCM buffers */
float *copy_buffers[MAX_PREPROC_CHANNELS];
#ifdef LIBSPEEXDSP_ENABLED
spx_int16_t *spx_segment_buffers[MAX_PREPROC_CHANNELS];
#endif
#ifdef LIBRNNOISE_ENABLED
float *rnn_segment_buffers[MAX_PREPROC_CHANNELS];
#endif
/* output data */
struct obs_audio_data output_audio;
DARRAY(float) output_data;
};
/* -------------------------------------------------------- */
#define SUP_MIN -60
#define SUP_MAX 0
#ifdef LIBSPEEXDSP_ENABLED
static const float c_32_to_16 = (float)INT16_MAX;
static const float c_16_to_32 = ((float)INT16_MAX + 1.0f);
#endif
/* -------------------------------------------------------- */
static const char *noise_suppress_name(void *unused)
{
UNUSED_PARAMETER(unused);
return obs_module_text("NoiseSuppress");
}
static void noise_suppress_destroy(void *data)
{
struct noise_suppress_data *ng = data;
for (size_t i = 0; i < ng->channels; i++) {
#ifdef LIBSPEEXDSP_ENABLED
speex_preprocess_state_destroy(ng->spx_states[i]);
#endif
#ifdef LIBRNNOISE_ENABLED
rnnoise_destroy(ng->rnn_states[i]);
#endif
deque_free(&ng->input_buffers[i]);
deque_free(&ng->output_buffers[i]);
}
#ifdef LIBSPEEXDSP_ENABLED
bfree(ng->spx_segment_buffers[0]);
#endif
#ifdef LIBRNNOISE_ENABLED
bfree(ng->rnn_segment_buffers[0]);
if (ng->rnn_resampler) {
audio_resampler_destroy(ng->rnn_resampler);
audio_resampler_destroy(ng->rnn_resampler_back);
}
#endif
bfree(ng->copy_buffers[0]);
deque_free(&ng->info_buffer);
da_free(ng->output_data);
bfree(ng);
}
static inline void alloc_channel(struct noise_suppress_data *ng, uint32_t sample_rate, size_t channel, size_t frames)
{
#ifdef LIBSPEEXDSP_ENABLED
ng->spx_states[channel] = speex_preprocess_state_init((int)frames, sample_rate);
#else
UNUSED_PARAMETER(sample_rate);
#endif
#ifdef LIBRNNOISE_ENABLED
ng->rnn_states[channel] = rnnoise_create(NULL);
#endif
deque_reserve(&ng->input_buffers[channel], frames * sizeof(float));
deque_reserve(&ng->output_buffers[channel], frames * sizeof(float));
}
static inline enum speaker_layout convert_speaker_layout(uint8_t channels)
{
switch (channels) {
case 0:
return SPEAKERS_UNKNOWN;
case 1:
return SPEAKERS_MONO;
case 2:
return SPEAKERS_STEREO;
case 3:
return SPEAKERS_2POINT1;
case 4:
return SPEAKERS_4POINT0;
case 5:
return SPEAKERS_4POINT1;
case 6:
return SPEAKERS_5POINT1;
case 8:
return SPEAKERS_7POINT1;
default:
return SPEAKERS_UNKNOWN;
}
}
static void noise_suppress_update(void *data, obs_data_t *s)
{
struct noise_suppress_data *ng = data;
uint32_t sample_rate = audio_output_get_sample_rate(obs_get_audio());
size_t channels = audio_output_get_channels(obs_get_audio());
size_t frames = (size_t)sample_rate / (1000 / BUFFER_SIZE_MSEC);
const char *method = obs_data_get_string(s, S_METHOD);
ng->suppress_level = (int)obs_data_get_int(s, S_SUPPRESS_LEVEL);
ng->latency = 1000000000LL / (1000 / BUFFER_SIZE_MSEC);
ng->use_rnnoise = strcmp(method, S_METHOD_RNN) == 0;
/* Process 10 millisecond segments to keep latency low. */
/* Also RNNoise only supports buffers of this exact size. */
ng->frames = frames;
ng->channels = channels;
/* Ignore if already allocated */
#if defined(LIBSPEEXDSP_ENABLED)
if (!ng->use_rnnoise && ng->spx_states[0])
return;
#endif
#ifdef LIBRNNOISE_ENABLED
if (ng->use_rnnoise && ng->rnn_states[0])
return;
#endif
/* One speex/rnnoise state for each channel (limit 2) */
ng->copy_buffers[0] = bmalloc(frames * channels * sizeof(float));
#ifdef LIBSPEEXDSP_ENABLED
ng->spx_segment_buffers[0] = bmalloc(frames * channels * sizeof(spx_int16_t));
#endif
#ifdef LIBRNNOISE_ENABLED
ng->rnn_segment_buffers[0] = bmalloc(RNNOISE_FRAME_SIZE * channels * sizeof(float));
#endif
for (size_t c = 1; c < channels; ++c) {
ng->copy_buffers[c] = ng->copy_buffers[c - 1] + frames;
#ifdef LIBSPEEXDSP_ENABLED
ng->spx_segment_buffers[c] = ng->spx_segment_buffers[c - 1] + frames;
#endif
#ifdef LIBRNNOISE_ENABLED
ng->rnn_segment_buffers[c] = ng->rnn_segment_buffers[c - 1] + RNNOISE_FRAME_SIZE;
#endif
}
for (size_t i = 0; i < channels; i++)
alloc_channel(ng, sample_rate, i, frames);
#ifdef LIBRNNOISE_ENABLED
if (sample_rate == RNNOISE_SAMPLE_RATE) {
ng->rnn_resampler = NULL;
ng->rnn_resampler_back = NULL;
} else {
struct resample_info src, dst;
src.samples_per_sec = sample_rate;
src.format = AUDIO_FORMAT_FLOAT_PLANAR;
src.speakers = convert_speaker_layout((uint8_t)channels);
dst.samples_per_sec = RNNOISE_SAMPLE_RATE;
dst.format = AUDIO_FORMAT_FLOAT_PLANAR;
dst.speakers = convert_speaker_layout((uint8_t)channels);
ng->rnn_resampler = audio_resampler_create(&dst, &src);
ng->rnn_resampler_back = audio_resampler_create(&src, &dst);
}
#endif
}
static void *noise_suppress_create(obs_data_t *settings, obs_source_t *filter)
{
struct noise_suppress_data *ng = bzalloc(sizeof(struct noise_suppress_data));
ng->context = filter;
ng->nvafx_enabled = false;
ng->nvafx_migrated = false;
#ifdef LIBNVAFX_ENABLED
ng->migrated_filter = NULL;
// If a NVAFX entry is detected, create a new instance of NVAFX filter.
const char *method = obs_data_get_string(settings, S_METHOD);
ng->nvafx_enabled = strcmp(method, S_METHOD_NVAFX_DENOISER) == 0 ||
strcmp(method, S_METHOD_NVAFX_DEREVERB) == 0 ||
strcmp(method, S_METHOD_NVAFX_DEREVERB_DENOISER) == 0;
if (ng->nvafx_enabled) {
const char *str1 = obs_source_get_name(filter);
char *str2 = "_ported";
char *new_name = (char *)bmalloc(1 + strlen(str1) + strlen(str2));
strcpy(new_name, str1);
strcat(new_name, str2);
obs_data_t *new_settings = obs_data_create();
obs_data_set_string(new_settings, S_METHOD, method);
double intensity = obs_data_get_double(settings, S_NVAFX_INTENSITY);
obs_data_set_double(new_settings, S_NVAFX_INTENSITY, intensity);
ng->migrated_filter = obs_source_create("nvidia_audiofx_filter", new_name, new_settings, NULL);
obs_data_release(new_settings);
bfree(new_name);
}
#endif
noise_suppress_update(ng, settings);
return ng;
}
static inline void process_speexdsp(struct noise_suppress_data *ng)
{
#ifdef LIBSPEEXDSP_ENABLED
/* Set args */
for (size_t i = 0; i < ng->channels; i++)
speex_preprocess_ctl(ng->spx_states[i], SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &ng->suppress_level);
/* Convert to 16bit */
for (size_t i = 0; i < ng->channels; i++)
for (size_t j = 0; j < ng->frames; j++) {
float s = ng->copy_buffers[i][j];
if (s > 1.0f)
s = 1.0f;
else if (s < -1.0f)
s = -1.0f;
ng->spx_segment_buffers[i][j] = (spx_int16_t)(s * c_32_to_16);
}
/* Execute */
for (size_t i = 0; i < ng->channels; i++)
speex_preprocess_run(ng->spx_states[i], ng->spx_segment_buffers[i]);
/* Convert back to 32bit */
for (size_t i = 0; i < ng->channels; i++)
for (size_t j = 0; j < ng->frames; j++)
ng->copy_buffers[i][j] = (float)ng->spx_segment_buffers[i][j] / c_16_to_32;
#else
UNUSED_PARAMETER(ng);
#endif
}
static inline void process_rnnoise(struct noise_suppress_data *ng)
{
#ifdef LIBRNNOISE_ENABLED
/* Adjust signal level to what RNNoise expects, resample if necessary */
if (ng->rnn_resampler) {
float *output[MAX_PREPROC_CHANNELS];
uint32_t out_frames;
uint64_t ts_offset;
audio_resampler_resample(ng->rnn_resampler, (uint8_t **)output, &out_frames, &ts_offset,
(const uint8_t **)ng->copy_buffers, (uint32_t)ng->frames);
for (size_t i = 0; i < ng->channels; i++) {
for (ssize_t j = 0, k = (ssize_t)out_frames - RNNOISE_FRAME_SIZE; j < RNNOISE_FRAME_SIZE;
++j, ++k) {
if (k >= 0) {
ng->rnn_segment_buffers[i][j] = output[i][k] * 32768.0f;
} else {
ng->rnn_segment_buffers[i][j] = 0;
}
}
}
} else {
for (size_t i = 0; i < ng->channels; i++) {
for (size_t j = 0; j < RNNOISE_FRAME_SIZE; ++j) {
ng->rnn_segment_buffers[i][j] = ng->copy_buffers[i][j] * 32768.0f;
}
}
}
/* Execute */
for (size_t i = 0; i < ng->channels; i++) {
rnnoise_process_frame(ng->rnn_states[i], ng->rnn_segment_buffers[i], ng->rnn_segment_buffers[i]);
}
/* Revert signal level adjustment, resample back if necessary */
if (ng->rnn_resampler) {
float *output[MAX_PREPROC_CHANNELS];
uint32_t out_frames;
uint64_t ts_offset;
audio_resampler_resample(ng->rnn_resampler_back, (uint8_t **)output, &out_frames, &ts_offset,
(const uint8_t **)ng->rnn_segment_buffers, RNNOISE_FRAME_SIZE);
for (size_t i = 0; i < ng->channels; i++) {
for (ssize_t j = 0, k = (ssize_t)out_frames - ng->frames; j < (ssize_t)ng->frames; ++j, ++k) {
if (k >= 0) {
ng->copy_buffers[i][j] = output[i][k] / 32768.0f;
} else {
ng->copy_buffers[i][j] = 0;
}
}
}
} else {
for (size_t i = 0; i < ng->channels; i++) {
for (size_t j = 0; j < RNNOISE_FRAME_SIZE; ++j) {
ng->copy_buffers[i][j] = ng->rnn_segment_buffers[i][j] / 32768.0f;
}
}
}
#else
UNUSED_PARAMETER(ng);
#endif
}
static inline void process(struct noise_suppress_data *ng)
{
if (ng->nvafx_enabled)
return;
/* Pop from input deque */
for (size_t i = 0; i < ng->channels; i++)
deque_pop_front(&ng->input_buffers[i], ng->copy_buffers[i], ng->frames * sizeof(float));
if (ng->use_rnnoise) {
process_rnnoise(ng);
} else {
process_speexdsp(ng);
}
/* Push to output deque */
for (size_t i = 0; i < ng->channels; i++)
deque_push_back(&ng->output_buffers[i], ng->copy_buffers[i], ng->frames * sizeof(float));
}
struct ng_audio_info {
uint32_t frames;
uint64_t timestamp;
};
static inline void clear_deque(struct deque *buf)
{
deque_pop_front(buf, NULL, buf->size);
}
static void reset_data(struct noise_suppress_data *ng)
{
for (size_t i = 0; i < ng->channels; i++) {
clear_deque(&ng->input_buffers[i]);
clear_deque(&ng->output_buffers[i]);
}
clear_deque(&ng->info_buffer);
}
#ifdef LIBNVAFX_ENABLED
static void noise_suppress_nvafx_migrate_task(void *param)
{
struct noise_suppress_data *ng = param;
obs_source_t *parent = obs_filter_get_parent(ng->context);
obs_source_filter_add(parent, ng->migrated_filter);
obs_source_set_enabled(ng->migrated_filter, obs_source_enabled(ng->context));
obs_source_filter_remove(parent, ng->context);
}
#endif
static struct obs_audio_data *noise_suppress_filter_audio(void *data, struct obs_audio_data *audio)
{
struct noise_suppress_data *ng = data;
struct ng_audio_info info;
size_t segment_size = ng->frames * sizeof(float);
size_t out_size;
obs_source_t *parent = obs_filter_get_parent(ng->context);
enum speaker_layout layout = obs_source_get_speaker_layout(parent);
ng->has_mono_src = layout == SPEAKERS_MONO && ng->channels == 2;
#ifdef LIBNVAFX_ENABLED
/* Migrate nvafx to new filter. */
if (ng->nvafx_enabled) {
if (!ng->nvafx_migrated) {
obs_queue_task(OBS_TASK_AUDIO, noise_suppress_nvafx_migrate_task, ng, false);
ng->nvafx_migrated = true;
}
return audio;
}
#endif
#ifdef LIBSPEEXDSP_ENABLED
if (!ng->spx_states[0])
return audio;
#endif
#ifdef LIBRNNOISE_ENABLED
if (!ng->rnn_states[0])
return audio;
#endif
/* -----------------------------------------------
* if timestamp has dramatically changed, consider it a new stream of
* audio data. clear all circular buffers to prevent old audio data
* from being processed as part of the new data. */
if (ng->last_timestamp) {
int64_t diff = llabs((int64_t)ng->last_timestamp - (int64_t)audio->timestamp);
if (diff > 1000000000LL)
reset_data(ng);
}
ng->last_timestamp = audio->timestamp;
/* -----------------------------------------------
* push audio packet info (timestamp/frame count) to info deque */
info.frames = audio->frames;
info.timestamp = audio->timestamp;
deque_push_back(&ng->info_buffer, &info, sizeof(info));
/* -----------------------------------------------
* push back current audio data to input deque */
for (size_t i = 0; i < ng->channels; i++)
deque_push_back(&ng->input_buffers[i], audio->data[i], audio->frames * sizeof(float));
/* -----------------------------------------------
* pop/process each 10ms segments, push back to output deque */
while (ng->input_buffers[0].size >= segment_size)
process(ng);
/* -----------------------------------------------
* peek front of info deque, check to see if we have enough to
* pop the expected packet size, if not, return null */
memset(&info, 0, sizeof(info));
deque_peek_front(&ng->info_buffer, &info, sizeof(info));
out_size = info.frames * sizeof(float);
if (ng->output_buffers[0].size < out_size)
return NULL;
/* -----------------------------------------------
* if there's enough audio data buffered in the output deque,
* pop and return a packet */
deque_pop_front(&ng->info_buffer, NULL, sizeof(info));
da_resize(ng->output_data, out_size * ng->channels);
for (size_t i = 0; i < ng->channels; i++) {
ng->output_audio.data[i] = (uint8_t *)&ng->output_data.array[i * out_size];
deque_pop_front(&ng->output_buffers[i], ng->output_audio.data[i], out_size);
}
ng->output_audio.frames = info.frames;
ng->output_audio.timestamp = info.timestamp - ng->latency;
return &ng->output_audio;
}
static bool noise_suppress_method_modified(obs_properties_t *props, obs_property_t *property, obs_data_t *settings)
{
obs_property_t *p_suppress_level = obs_properties_get(props, S_SUPPRESS_LEVEL);
obs_property_t *p_navfx_intensity = obs_properties_get(props, S_NVAFX_INTENSITY);
const char *method = obs_data_get_string(settings, S_METHOD);
bool enable_level = strcmp(method, S_METHOD_SPEEX) == 0;
bool enable_intensity = strcmp(method, S_METHOD_NVAFX_DENOISER) == 0 ||
strcmp(method, S_METHOD_NVAFX_DEREVERB) == 0 ||
strcmp(method, S_METHOD_NVAFX_DEREVERB_DENOISER) == 0;
obs_property_set_visible(p_suppress_level, enable_level);
obs_property_set_visible(p_navfx_intensity, enable_intensity);
UNUSED_PARAMETER(property);
return true;
}
static void noise_suppress_defaults_v1(obs_data_t *s)
{
obs_data_set_default_int(s, S_SUPPRESS_LEVEL, -30);
#if defined(LIBRNNOISE_ENABLED) && !defined(LIBSPEEXDSP_ENABLED)
obs_data_set_default_string(s, S_METHOD, S_METHOD_RNN);
#else
obs_data_set_default_string(s, S_METHOD, S_METHOD_SPEEX);
#endif
#if defined(LIBNVAFX_ENABLED)
obs_data_set_default_double(s, S_NVAFX_INTENSITY, 1.0);
#endif
}
static void noise_suppress_defaults_v2(obs_data_t *s)
{
obs_data_set_default_int(s, S_SUPPRESS_LEVEL, -30);
#if defined(LIBRNNOISE_ENABLED)
obs_data_set_default_string(s, S_METHOD, S_METHOD_RNN);
#else
obs_data_set_default_string(s, S_METHOD, S_METHOD_SPEEX);
#endif
#if defined(LIBNVAFX_ENABLED)
obs_data_set_default_double(s, S_NVAFX_INTENSITY, 1.0);
#endif
}
static obs_properties_t *noise_suppress_properties(void *data)
{
obs_properties_t *ppts = obs_properties_create();
#ifdef LIBNVAFX_ENABLED
struct noise_suppress_data *ng = (struct noise_suppress_data *)data;
#else
UNUSED_PARAMETER(data);
#endif
#if defined(LIBRNNOISE_ENABLED) && defined(LIBSPEEXDSP_ENABLED)
obs_property_t *method =
obs_properties_add_list(ppts, S_METHOD, TEXT_METHOD, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
obs_property_list_add_string(method, TEXT_METHOD_SPEEX, S_METHOD_SPEEX);
obs_property_list_add_string(method, TEXT_METHOD_RNN, S_METHOD_RNN);
#ifdef LIBNVAFX_ENABLED
if (ng->nvafx_enabled) {
obs_property_list_add_string(method, TEXT_METHOD_NVAFX_DENOISER, S_METHOD_NVAFX_DENOISER);
obs_property_list_add_string(method, TEXT_METHOD_NVAFX_DEREVERB, S_METHOD_NVAFX_DEREVERB);
obs_property_list_add_string(method, TEXT_METHOD_NVAFX_DEREVERB_DENOISER,
S_METHOD_NVAFX_DEREVERB_DENOISER);
obs_property_list_item_disable(method, 2, true);
obs_property_list_item_disable(method, 3, true);
obs_property_list_item_disable(method, 4, true);
}
#endif
obs_property_set_modified_callback(method, noise_suppress_method_modified);
#endif
#ifdef LIBSPEEXDSP_ENABLED
obs_property_t *speex_slider =
obs_properties_add_int_slider(ppts, S_SUPPRESS_LEVEL, TEXT_SUPPRESS_LEVEL, SUP_MIN, SUP_MAX, 1);
obs_property_int_set_suffix(speex_slider, " dB");
#endif
#ifdef LIBNVAFX_ENABLED
if (ng->nvafx_enabled) {
obs_properties_add_float_slider(ppts, S_NVAFX_INTENSITY, TEXT_NVAFX_INTENSITY, 0.0f, 1.0f, 0.01f);
obs_property_t *warning2 = obs_properties_add_text(ppts, "deprecation2", NULL, OBS_TEXT_INFO);
obs_property_text_set_info_type(warning2, OBS_TEXT_INFO_WARNING);
obs_property_set_long_description(warning2, TEXT_METHOD_NVAFX_DEPRECATION2);
}
#if defined(LIBRNNOISE_ENABLED) && defined(LIBSPEEXDSP_ENABLED)
if (!nvafx_loaded) {
obs_property_list_item_disable(method, 2, true);
obs_property_list_item_disable(method, 3, true);
obs_property_list_item_disable(method, 4, true);
}
#endif
#endif
return ppts;
}
struct obs_source_info noise_suppress_filter = {
.id = "noise_suppress_filter",
.type = OBS_SOURCE_TYPE_FILTER,
.output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_CAP_OBSOLETE,
.get_name = noise_suppress_name,
.create = noise_suppress_create,
.destroy = noise_suppress_destroy,
.update = noise_suppress_update,
.filter_audio = noise_suppress_filter_audio,
.get_defaults = noise_suppress_defaults_v1,
.get_properties = noise_suppress_properties,
};
struct obs_source_info noise_suppress_filter_v2 = {
.id = "noise_suppress_filter",
.version = 2,
.type = OBS_SOURCE_TYPE_FILTER,
.output_flags = OBS_SOURCE_AUDIO,
.get_name = noise_suppress_name,
.create = noise_suppress_create,
.destroy = noise_suppress_destroy,
.update = noise_suppress_update,
.filter_audio = noise_suppress_filter_audio,
.get_defaults = noise_suppress_defaults_v2,
.get_properties = noise_suppress_properties,
};
| 20,828 |
C
|
.c
| 577 | 33.892548 | 117 | 0.701086 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
2,464 |
xcomposite-input.c
|
obsproject_obs-studio/plugins/linux-capture/xcomposite-input.c
|
#include <obs-module.h>
#include <obs-nix-platform.h>
#include <glad/glad.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xlib-xcb.h>
#include <xcb/xcb.h>
#include <xcb/composite.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <ctype.h>
#include "xhelpers.h"
#include "xcursor-xcb.h"
#include "xcomposite-input.h"
#include <util/platform.h>
#include <util/dstr.h>
#include <util/darray.h>
#define WIN_STRING_DIV "\r\n"
#define FIND_WINDOW_INTERVAL 2.0
static Display *disp = NULL;
static xcb_connection_t *conn = NULL;
// Atoms used throughout our plugin
xcb_atom_t ATOM_UTF8_STRING;
xcb_atom_t ATOM_STRING;
xcb_atom_t ATOM_TEXT;
xcb_atom_t ATOM_COMPOUND_TEXT;
xcb_atom_t ATOM_WM_NAME;
xcb_atom_t ATOM_WM_CLASS;
xcb_atom_t ATOM__NET_WM_NAME;
xcb_atom_t ATOM__NET_SUPPORTING_WM_CHECK;
xcb_atom_t ATOM__NET_CLIENT_LIST;
struct xcompcap {
obs_source_t *source;
const char *windowName;
xcb_window_t win;
int crop_top;
int crop_left;
int crop_right;
int crop_bot;
bool include_border;
bool exclude_alpha;
float window_check_time;
bool window_changed;
bool window_hooked;
uint32_t width;
uint32_t height;
uint32_t border;
Pixmap pixmap;
gs_texture_t *gltex;
pthread_mutex_t lock;
bool show_cursor;
bool cursor_outside;
xcb_xcursor_t *cursor;
};
static void xcompcap_update(void *data, obs_data_t *settings);
static xcb_window_t convert_encoded_window_id(const char *str, char **p_wname, char **p_wcls);
xcb_atom_t get_atom(xcb_connection_t *conn, const char *name)
{
xcb_intern_atom_cookie_t atom_c = xcb_intern_atom(conn, 1, strlen(name), name);
xcb_intern_atom_reply_t *atom_r = xcb_intern_atom_reply(conn, atom_c, NULL);
xcb_atom_t a = atom_r->atom;
free(atom_r);
return a;
}
void xcomp_gather_atoms(xcb_connection_t *conn)
{
ATOM_UTF8_STRING = get_atom(conn, "UTF8_STRING");
ATOM_STRING = get_atom(conn, "STRING");
ATOM_TEXT = get_atom(conn, "TEXT");
ATOM_COMPOUND_TEXT = get_atom(conn, "COMPOUND_TEXT");
ATOM_WM_NAME = get_atom(conn, "WM_NAME");
ATOM_WM_CLASS = get_atom(conn, "WM_CLASS");
ATOM__NET_WM_NAME = get_atom(conn, "_NET_WM_NAME");
ATOM__NET_SUPPORTING_WM_CHECK = get_atom(conn, "_NET_SUPPORTING_WM_CHECK");
ATOM__NET_CLIENT_LIST = get_atom(conn, "_NET_CLIENT_LIST");
}
bool xcomp_window_exists(xcb_connection_t *conn, xcb_window_t win)
{
xcb_generic_error_t *err = NULL;
xcb_get_window_attributes_cookie_t attr_cookie = xcb_get_window_attributes(conn, win);
xcb_get_window_attributes_reply_t *attr = xcb_get_window_attributes_reply(conn, attr_cookie, &err);
bool exists = err == NULL && attr->map_state == XCB_MAP_STATE_VIEWABLE;
free(attr);
return exists;
}
xcb_get_property_reply_t *xcomp_property_sync(xcb_connection_t *conn, xcb_window_t win, xcb_atom_t atom)
{
if (atom == XCB_ATOM_NONE)
return NULL;
xcb_generic_error_t *err = NULL;
// Read properties up to 4096*4 bytes
xcb_get_property_cookie_t prop_cookie = xcb_get_property(conn, 0, win, atom, 0, 0, 4096);
xcb_get_property_reply_t *prop = xcb_get_property_reply(conn, prop_cookie, &err);
if (err != NULL || xcb_get_property_value_length(prop) == 0) {
free(prop);
return NULL;
}
return prop;
}
// See ICCCM https://www.x.org/releases/X11R7.6/doc/xorg-docs/specs/ICCCM/icccm.html#text_properties
// for more info on the galactic brained string types used in Xorg.
struct dstr xcomp_window_name(xcb_connection_t *conn, Display *disp, xcb_window_t win)
{
struct dstr ret = {0};
xcb_get_property_reply_t *name = xcomp_property_sync(conn, win, ATOM__NET_WM_NAME);
if (name) {
// Guaranteed to be UTF8_STRING.
const char *data = (const char *)xcb_get_property_value(name);
dstr_ncopy(&ret, data, xcb_get_property_value_length(name));
free(name);
return ret;
}
name = xcomp_property_sync(conn, win, ATOM_WM_NAME);
if (!name) {
goto fail;
}
char *data = (char *)xcb_get_property_value(name);
if (name->type == ATOM_UTF8_STRING) {
dstr_ncopy(&ret, data, xcb_get_property_value_length(name));
free(name);
return ret;
}
if (name->type == ATOM_STRING) { // Latin-1, safe enough
dstr_ncopy(&ret, data, xcb_get_property_value_length(name));
free(name);
return ret;
}
if (name->type == ATOM_TEXT) { // Default charset
char *utf8;
if (!os_mbs_to_utf8_ptr(data, xcb_get_property_value_length(name), &utf8)) {
free(name);
goto fail;
}
free(name);
dstr_init_move_array(&ret, utf8);
return ret;
}
if (name->type == ATOM_COMPOUND_TEXT) { // LibX11 is the only decoder for these.
XTextProperty xname = {
(unsigned char *)data, name->type,
8, // 8 by definition.
1, // Only decode the first element of string arrays.
};
char **list;
int len = 0;
if (XmbTextPropertyToTextList(disp, &xname, &list, &len) < Success || !list || len < 1) {
free(name);
goto fail;
}
char *utf8;
if (!os_mbs_to_utf8_ptr(list[0], 0, &utf8)) {
XFreeStringList(list);
free(name);
goto fail;
}
dstr_init_move_array(&ret, utf8);
XFreeStringList(list);
free(name);
return ret;
}
fail:
dstr_copy(&ret, "unknown");
return ret;
}
struct dstr xcomp_window_class(xcb_connection_t *conn, xcb_window_t win)
{
struct dstr ret = {0};
dstr_copy(&ret, "unknown");
xcb_get_property_reply_t *cls = xcomp_property_sync(conn, win, ATOM_WM_CLASS);
if (!cls)
return ret;
// WM_CLASS is formatted differently from other strings, it's two null terminated strings.
// Since we want the first one, let's just let copy run strlen.
dstr_copy(&ret, (const char *)xcb_get_property_value(cls));
free(cls);
return ret;
}
// Specification for checking for ewmh support at
// http://standards.freedesktop.org/wm-spec/wm-spec-latest.html#idm140200472693600
bool xcomp_check_ewmh(xcb_connection_t *conn, xcb_window_t root)
{
xcb_get_property_reply_t *check = xcomp_property_sync(conn, root, ATOM__NET_SUPPORTING_WM_CHECK);
if (!check)
return false;
xcb_window_t ewmh_window = ((xcb_window_t *)xcb_get_property_value(check))[0];
free(check);
xcb_get_property_reply_t *check2 = xcomp_property_sync(conn, ewmh_window, ATOM__NET_SUPPORTING_WM_CHECK);
if (!check2)
return false;
free(check2);
return true;
}
struct darray xcomp_top_level_windows(xcb_connection_t *conn)
{
DARRAY(xcb_window_t) res = {0};
// EWMH top level window listing is not supported.
if (ATOM__NET_CLIENT_LIST == XCB_ATOM_NONE)
return res.da;
xcb_screen_iterator_t screen_iter = xcb_setup_roots_iterator(xcb_get_setup(conn));
for (; screen_iter.rem > 0; xcb_screen_next(&screen_iter)) {
xcb_generic_error_t *err = NULL;
// Read properties up to 4096*4 bytes
xcb_get_property_cookie_t cl_list_cookie =
xcb_get_property(conn, 0, screen_iter.data->root, ATOM__NET_CLIENT_LIST, 0, 0, 4096);
xcb_get_property_reply_t *cl_list = xcb_get_property_reply(conn, cl_list_cookie, &err);
if (err != NULL) {
goto done;
}
uint32_t len = xcb_get_property_value_length(cl_list) / sizeof(xcb_window_t);
for (uint32_t i = 0; i < len; i++)
da_push_back(res, &(((xcb_window_t *)xcb_get_property_value(cl_list))[i]));
done:
free(cl_list);
}
return res.da;
}
static xcb_window_t convert_encoded_window_id(const char *str, char **p_wname, char **p_wcls)
{
size_t markSize = strlen(WIN_STRING_DIV);
const char *firstMark = strstr(str, WIN_STRING_DIV);
const char *secondMark = firstMark ? strstr(firstMark + markSize, WIN_STRING_DIV) : NULL;
const char *strEnd = str + strlen(str);
const char *secondStr = firstMark + markSize;
const char *thirdStr = secondMark + markSize;
// wstr only consists of the window-id
if (!firstMark) {
*p_wname = NULL;
*p_wcls = NULL;
return (xcb_window_t)atol(str);
}
// wstr also contains window-name and window-class
char *wname = bzalloc(secondMark - secondStr + 1);
char *wcls = bzalloc(strEnd - thirdStr + 1);
memcpy(wname, secondStr, secondMark - secondStr);
memcpy(wcls, thirdStr, strEnd - thirdStr);
xcb_window_t ret = (xcb_window_t)strtol(str, NULL, 10);
*p_wname = wname;
*p_wcls = wcls;
return ret;
}
xcb_window_t xcomp_find_window(xcb_connection_t *conn, Display *disp, const char *str)
{
xcb_window_t ret = 0;
char *wname = NULL;
char *wcls = NULL;
DARRAY(xcb_window_t) tlw = {0};
if (!str || strlen(str) == 0) {
goto cleanup;
}
ret = convert_encoded_window_id(str, &wname, &wcls);
// first try to find a match by the window-id
tlw.da = xcomp_top_level_windows(conn);
if (da_find(tlw, &ret, 0) != DARRAY_INVALID) {
goto cleanup;
}
// then try to find a match by name & class
for (size_t i = 0; i < tlw.num; i++) {
xcb_window_t cwin = *(xcb_window_t *)darray_item(sizeof(xcb_window_t), &tlw.da, i);
struct dstr cwname = xcomp_window_name(conn, disp, cwin);
struct dstr cwcls = xcomp_window_class(conn, cwin);
bool found = dstr_cmp(&cwname, wname) == 0 && dstr_cmp(&cwcls, wcls) == 0;
dstr_free(&cwname);
dstr_free(&cwcls);
if (found) {
ret = cwin;
goto cleanup;
}
}
blog(LOG_DEBUG, "Did not find new window id for Name '%s' or Class '%s'", wname, wcls);
cleanup:
bfree(wname);
bfree(wcls);
da_free(tlw);
return ret;
}
void xcomp_cleanup_pixmap(Display *disp, struct xcompcap *s)
{
if (s->gltex) {
gs_texture_destroy(s->gltex);
s->gltex = 0;
}
if (s->pixmap) {
XFreePixmap(disp, s->pixmap);
s->pixmap = 0;
}
}
static int silence_x11_errors(Display *display, XErrorEvent *err)
{
UNUSED_PARAMETER(display);
UNUSED_PARAMETER(err);
return 0;
}
void xcomp_create_pixmap(xcb_connection_t *conn, struct xcompcap *s, int log_level)
{
if (!s->win)
return;
xcb_generic_error_t *err = NULL;
xcb_get_geometry_cookie_t geom_cookie = xcb_get_geometry(conn, s->win);
xcb_get_geometry_reply_t *geom = xcb_get_geometry_reply(conn, geom_cookie, &err);
if (err != NULL) {
return;
}
s->border = s->include_border ? geom->border_width : 0;
s->width = geom->width;
s->height = geom->height;
// We don't have an alpha channel, but may have garbage in the texture.
int32_t depth = geom->depth;
if (depth != 32) {
s->exclude_alpha = true;
}
free(geom);
uint32_t vert_borders = s->crop_top + s->crop_bot + 2 * s->border;
uint32_t hori_borders = s->crop_left + s->crop_right + 2 * s->border;
// Skip 0 sized textures.
if (vert_borders > s->height || hori_borders > s->width)
return;
s->pixmap = xcb_generate_id(conn);
xcb_void_cookie_t name_cookie = xcb_composite_name_window_pixmap_checked(conn, s->win, s->pixmap);
err = NULL;
if ((err = xcb_request_check(conn, name_cookie)) != NULL) {
blog(log_level, "xcb_composite_name_window_pixmap failed");
s->pixmap = 0;
return;
}
XErrorHandler prev = XSetErrorHandler(silence_x11_errors);
s->gltex = gs_texture_create_from_pixmap(s->width, s->height, GS_BGRA_UNORM, GL_TEXTURE_2D, (void *)s->pixmap);
XSetErrorHandler(prev);
}
struct reg_item {
struct xcompcap *src;
xcb_window_t win;
};
static DARRAY(struct reg_item) watcher_registry = {0};
static pthread_mutex_t watcher_lock = PTHREAD_MUTEX_INITIALIZER;
void watcher_register(xcb_connection_t *conn, struct xcompcap *s)
{
pthread_mutex_lock(&watcher_lock);
if (xcomp_window_exists(conn, s->win)) {
// Subscribe to Events
uint32_t vals[1] = {StructureNotifyMask | ExposureMask | VisibilityChangeMask};
xcb_change_window_attributes(conn, s->win, XCB_CW_EVENT_MASK, vals);
xcb_composite_redirect_window(conn, s->win, XCB_COMPOSITE_REDIRECT_AUTOMATIC);
da_push_back(watcher_registry, (&(struct reg_item){s, s->win}));
}
pthread_mutex_unlock(&watcher_lock);
}
void watcher_unregister(xcb_connection_t *conn, struct xcompcap *s)
{
pthread_mutex_lock(&watcher_lock);
size_t idx = DARRAY_INVALID;
xcb_window_t win = 0;
for (size_t i = 0; i < watcher_registry.num; i++) {
struct reg_item *item =
(struct reg_item *)darray_item(sizeof(struct reg_item), &watcher_registry.da, i);
if (item->src == s) {
idx = i;
win = item->win;
break;
}
}
if (idx == DARRAY_INVALID)
goto done;
da_erase(watcher_registry, idx);
// Check if there are still sources listening for the same window.
bool windowInUse = false;
for (size_t i = 0; i < watcher_registry.num; i++) {
struct reg_item *item =
(struct reg_item *)darray_item(sizeof(struct reg_item), &watcher_registry.da, i);
if (item->win == win) {
windowInUse = true;
break;
}
}
if (!windowInUse && xcomp_window_exists(conn, s->win)) {
// Last source released, stop listening for events.
uint32_t vals[1] = {0};
xcb_change_window_attributes(conn, win, XCB_CW_EVENT_MASK, vals);
}
done:
pthread_mutex_unlock(&watcher_lock);
}
void watcher_process(xcb_generic_event_t *ev)
{
if (!ev)
return;
pthread_mutex_lock(&watcher_lock);
xcb_window_t win = 0;
switch (ev->response_type & ~0x80) {
case XCB_CONFIGURE_NOTIFY:
win = ((xcb_configure_notify_event_t *)ev)->event;
break;
case XCB_MAP_NOTIFY:
win = ((xcb_map_notify_event_t *)ev)->event;
break;
case XCB_EXPOSE:
win = ((xcb_expose_event_t *)ev)->window;
break;
case XCB_VISIBILITY_NOTIFY:
win = ((xcb_visibility_notify_event_t *)ev)->window;
break;
case XCB_DESTROY_NOTIFY:
win = ((xcb_destroy_notify_event_t *)ev)->event;
break;
};
if (win != 0) {
for (size_t i = 0; i < watcher_registry.num; i++) {
struct reg_item *item =
(struct reg_item *)darray_item(sizeof(struct reg_item), &watcher_registry.da, i);
if (item->win == win) {
item->src->window_changed = true;
}
}
}
pthread_mutex_unlock(&watcher_lock);
}
void watcher_unload()
{
da_free(watcher_registry);
}
static void xcompcap_get_hooked(void *data, calldata_t *cd)
{
struct xcompcap *s = data;
if (!s)
return;
calldata_set_bool(cd, "hooked", s->window_hooked);
if (s->window_hooked) {
struct dstr wname = xcomp_window_name(conn, disp, s->win);
struct dstr wcls = xcomp_window_class(conn, s->win);
calldata_set_string(cd, "name", wname.array);
calldata_set_string(cd, "class", wcls.array);
dstr_free(&wname);
dstr_free(&wcls);
} else {
calldata_set_string(cd, "name", "");
calldata_set_string(cd, "class", "");
}
}
static uint32_t xcompcap_get_width(void *data)
{
struct xcompcap *s = (struct xcompcap *)data;
if (!s->gltex)
return 0;
int32_t border = s->crop_left + s->crop_right + 2 * s->border;
int32_t width = s->width - border;
return width < 0 ? 0 : width;
}
static uint32_t xcompcap_get_height(void *data)
{
struct xcompcap *s = (struct xcompcap *)data;
if (!s->gltex)
return 0;
int32_t border = s->crop_bot + s->crop_top + 2 * s->border;
int32_t height = s->height - border;
return height < 0 ? 0 : height;
}
static void *xcompcap_create(obs_data_t *settings, obs_source_t *source)
{
struct xcompcap *s = (struct xcompcap *)bzalloc(sizeof(struct xcompcap));
pthread_mutex_init(&s->lock, NULL);
s->show_cursor = true;
s->source = source;
s->window_hooked = false;
obs_enter_graphics();
s->cursor = xcb_xcursor_init(conn);
obs_leave_graphics();
signal_handler_t *sh = obs_source_get_signal_handler(source);
signal_handler_add(sh, "void unhooked(ptr source)");
signal_handler_add(sh, "void hooked(ptr source, string name, string class)");
proc_handler_t *ph = obs_source_get_proc_handler(source);
proc_handler_add(ph, "void get_hooked(out bool hooked, out string name, out string class)", xcompcap_get_hooked,
s);
xcompcap_update(s, settings);
return s;
}
static void xcompcap_destroy(void *data)
{
struct xcompcap *s = (struct xcompcap *)data;
obs_enter_graphics();
pthread_mutex_lock(&s->lock);
watcher_unregister(conn, s);
xcomp_cleanup_pixmap(disp, s);
if (s->cursor)
xcb_xcursor_destroy(s->cursor);
pthread_mutex_unlock(&s->lock);
obs_leave_graphics();
pthread_mutex_destroy(&s->lock);
bfree(s);
}
static void xcompcap_video_tick(void *data, float seconds)
{
struct xcompcap *s = (struct xcompcap *)data;
if (!obs_source_showing(s->source))
return;
obs_enter_graphics();
pthread_mutex_lock(&s->lock);
xcb_generic_event_t *event;
while ((event = xcb_poll_for_queued_event(conn)))
watcher_process(event);
// Send an unhooked signal if the window isn't found anymore
if (s->window_hooked && !xcomp_window_exists(conn, s->win)) {
s->window_hooked = false;
signal_handler_t *sh = obs_source_get_signal_handler(s->source);
calldata_t data = {0};
calldata_set_ptr(&data, "source", s->source);
signal_handler_signal(sh, "unhooked", &data);
calldata_free(&data);
}
// Reacquire window after interval or immediately if reconfigured.
s->window_check_time += seconds;
bool window_lost = !xcomp_window_exists(conn, s->win) || !s->gltex;
if ((window_lost && s->window_check_time > FIND_WINDOW_INTERVAL) || s->window_changed) {
watcher_unregister(conn, s);
s->window_changed = false;
s->window_check_time = 0.0;
s->win = xcomp_find_window(conn, disp, s->windowName);
// Send a hooked signal if a new window has been found
if (!s->window_hooked && xcomp_window_exists(conn, s->win)) {
s->window_hooked = true;
signal_handler_t *sh = obs_source_get_signal_handler(s->source);
calldata_t data = {0};
calldata_set_ptr(&data, "source", s->source);
struct dstr wname = xcomp_window_name(conn, disp, s->win);
struct dstr wcls = xcomp_window_class(conn, s->win);
calldata_set_string(&data, "name", wname.array);
calldata_set_string(&data, "class", wcls.array);
signal_handler_signal(sh, "hooked", &data);
dstr_free(&wname);
dstr_free(&wcls);
calldata_free(&data);
}
watcher_register(conn, s);
xcomp_cleanup_pixmap(disp, s);
// Avoid excessive logging. We expect this to fail while windows are
// minimized or on offscreen workspaces or already captured on NVIDIA.
xcomp_create_pixmap(conn, s, LOG_DEBUG);
xcb_xcursor_offset_win(conn, s->cursor, s->win);
xcb_xcursor_offset(s->cursor, s->cursor->x_org + s->crop_left, s->cursor->y_org + s->crop_top);
}
if (!s->gltex)
goto done;
if (xcompcap_get_height(s) == 0 || xcompcap_get_width(s) == 0)
goto done;
if (s->show_cursor) {
xcb_xcursor_update(conn, s->cursor);
s->cursor_outside = s->cursor->x < 0 || s->cursor->y < 0 || s->cursor->x > (int)xcompcap_get_width(s) ||
s->cursor->y > (int)xcompcap_get_height(s);
}
done:
pthread_mutex_unlock(&s->lock);
obs_leave_graphics();
}
static void xcompcap_video_render(void *data, gs_effect_t *effect)
{
gs_eparam_t *image; // Placate C++ goto rules.
struct xcompcap *s = (struct xcompcap *)data;
pthread_mutex_lock(&s->lock);
if (!s->gltex)
goto done;
effect = obs_get_base_effect(OBS_EFFECT_DEFAULT);
if (s->exclude_alpha)
effect = obs_get_base_effect(OBS_EFFECT_OPAQUE);
image = gs_effect_get_param_by_name(effect, "image");
gs_effect_set_texture(image, s->gltex);
while (gs_effect_loop(effect, "Draw")) {
gs_draw_sprite_subregion(s->gltex, 0, s->crop_left, s->crop_top, xcompcap_get_width(s),
xcompcap_get_height(s));
}
if (s->gltex && s->show_cursor && !s->cursor_outside) {
effect = obs_get_base_effect(OBS_EFFECT_DEFAULT);
while (gs_effect_loop(effect, "Draw")) {
xcb_xcursor_render(s->cursor);
}
}
done:
pthread_mutex_unlock(&s->lock);
}
struct WindowInfo {
struct dstr name_lower;
struct dstr name;
struct dstr desc;
};
static int cmp_wi(const void *a, const void *b)
{
struct WindowInfo *awi = (struct WindowInfo *)a;
struct WindowInfo *bwi = (struct WindowInfo *)b;
const char *a_name = awi->name_lower.array ? awi->name_lower.array : "";
const char *b_name = bwi->name_lower.array ? bwi->name_lower.array : "";
return strcmp(a_name, b_name);
}
static inline bool compare_ids(const char *id1, const char *id2)
{
if (!id1 || !id2)
return false;
id1 = strstr(id1, "\r\n");
id2 = strstr(id2, "\r\n");
return id1 && id2 && strcmp(id1, id2) == 0;
}
static obs_properties_t *xcompcap_props(void *data)
{
struct xcompcap *s = (struct xcompcap *)data;
obs_properties_t *props = obs_properties_create();
obs_property_t *prop;
prop = obs_properties_add_list(props, "capture_window", obs_module_text("Window"), OBS_COMBO_TYPE_LIST,
OBS_COMBO_FORMAT_STRING);
DARRAY(struct WindowInfo) window_strings = {0};
bool had_window_saved = false;
if (s) {
had_window_saved = s->windowName && *s->windowName;
if (had_window_saved) {
char *wname;
char *wcls;
convert_encoded_window_id(s->windowName, &wname, &wcls);
bfree(wcls);
struct dstr name = {0};
struct dstr desc = {0};
struct dstr name_lower = {0};
dstr_copy(&name, wname ? wname : obs_module_text("UnknownWindow"));
bfree(wname);
dstr_copy(&desc, s->windowName);
dstr_copy_dstr(&name_lower, &name);
dstr_to_lower(&name_lower);
da_push_back(window_strings, (&(struct WindowInfo){name_lower, name, desc}));
} else {
struct dstr select_window_str;
dstr_init_copy(&select_window_str, obs_module_text("SelectAWindow"));
da_push_back(window_strings, (&(struct WindowInfo){{0}, select_window_str, {0}}));
}
}
struct darray windows = xcomp_top_level_windows(conn);
bool window_found = false;
for (size_t w = 0; w < windows.num; w++) {
xcb_window_t win = *(xcb_window_t *)darray_item(sizeof(xcb_window_t), &windows, w);
struct dstr name = xcomp_window_name(conn, disp, win);
struct dstr cls = xcomp_window_class(conn, win);
struct dstr desc = {0};
dstr_printf(&desc, "%d" WIN_STRING_DIV "%s" WIN_STRING_DIV "%s", win, name.array, cls.array);
dstr_free(&cls);
struct dstr name_lower;
dstr_init_copy_dstr(&name_lower, &name);
dstr_to_lower(&name_lower);
if (!had_window_saved || (s && !compare_ids(desc.array, s->windowName)))
da_push_back(window_strings, (&(struct WindowInfo){name_lower, name, desc}));
else {
window_found = true;
dstr_free(&name);
dstr_free(&name_lower);
dstr_free(&desc);
}
}
darray_free(&windows);
if (window_strings.num > 2)
qsort(window_strings.array + 1, window_strings.num - 1, sizeof(struct WindowInfo), cmp_wi);
for (size_t i = 0; i < window_strings.num; i++) {
struct WindowInfo *w =
(struct WindowInfo *)darray_item(sizeof(struct WindowInfo), &window_strings.da, i);
obs_property_list_add_string(prop, w->name.array, w->desc.array);
dstr_free(&w->name_lower);
dstr_free(&w->name);
dstr_free(&w->desc);
}
da_free(window_strings);
if (!had_window_saved || !window_found) {
obs_property_list_item_disable(prop, 0, true);
}
prop = obs_properties_add_int(props, "cut_top", obs_module_text("CropTop"), 0, 4096, 1);
obs_property_int_set_suffix(prop, " px");
prop = obs_properties_add_int(props, "cut_left", obs_module_text("CropLeft"), 0, 4096, 1);
obs_property_int_set_suffix(prop, " px");
prop = obs_properties_add_int(props, "cut_right", obs_module_text("CropRight"), 0, 4096, 1);
obs_property_int_set_suffix(prop, " px");
prop = obs_properties_add_int(props, "cut_bot", obs_module_text("CropBottom"), 0, 4096, 1);
obs_property_int_set_suffix(prop, " px");
obs_properties_add_bool(props, "show_cursor", obs_module_text("CaptureCursor"));
obs_properties_add_bool(props, "include_border", obs_module_text("IncludeXBorder"));
obs_properties_add_bool(props, "exclude_alpha", obs_module_text("ExcludeAlpha"));
return props;
}
static void xcompcap_defaults(obs_data_t *settings)
{
obs_data_set_default_string(settings, "capture_window", "");
obs_data_set_default_int(settings, "cut_top", 0);
obs_data_set_default_int(settings, "cut_left", 0);
obs_data_set_default_int(settings, "cut_right", 0);
obs_data_set_default_int(settings, "cut_bot", 0);
obs_data_set_default_bool(settings, "show_cursor", true);
obs_data_set_default_bool(settings, "include_border", false);
obs_data_set_default_bool(settings, "exclude_alpha", false);
}
static void xcompcap_update(void *data, obs_data_t *settings)
{
struct xcompcap *s = (struct xcompcap *)data;
obs_enter_graphics();
pthread_mutex_lock(&s->lock);
char *prev_name = bstrdup(s->windowName);
s->crop_top = obs_data_get_int(settings, "cut_top");
s->crop_left = obs_data_get_int(settings, "cut_left");
s->crop_right = obs_data_get_int(settings, "cut_right");
s->crop_bot = obs_data_get_int(settings, "cut_bot");
s->show_cursor = obs_data_get_bool(settings, "show_cursor");
s->include_border = obs_data_get_bool(settings, "include_border");
s->exclude_alpha = obs_data_get_bool(settings, "exclude_alpha");
s->windowName = obs_data_get_string(settings, "capture_window");
if (s->window_hooked && strcmp(prev_name, s->windowName) != 0) {
s->window_hooked = false;
signal_handler_t *sh = obs_source_get_signal_handler(s->source);
calldata_t data = {0};
calldata_set_ptr(&data, "source", s->source);
signal_handler_signal(sh, "unhooked", &data);
calldata_free(&data);
}
bfree(prev_name);
s->win = xcomp_find_window(conn, disp, s->windowName);
if (!s->window_hooked && xcomp_window_exists(conn, s->win)) {
s->window_hooked = true;
signal_handler_t *sh = obs_source_get_signal_handler(s->source);
calldata_t data = {0};
calldata_set_ptr(&data, "source", s->source);
struct dstr wname = xcomp_window_name(conn, disp, s->win);
struct dstr wcls = xcomp_window_class(conn, s->win);
calldata_set_string(&data, "name", wname.array);
calldata_set_string(&data, "class", wcls.array);
signal_handler_signal(sh, "hooked", &data);
dstr_free(&wname);
dstr_free(&wcls);
calldata_free(&data);
}
if (s->win && s->windowName) {
struct dstr wname = xcomp_window_name(conn, disp, s->win);
struct dstr wcls = xcomp_window_class(conn, s->win);
blog(LOG_INFO,
"[window-capture: '%s'] update settings:\n"
"\ttitle: %s\n"
"\tclass: %s\n",
obs_source_get_name(s->source), wname.array, wcls.array);
dstr_free(&wname);
dstr_free(&wcls);
}
watcher_register(conn, s);
xcomp_cleanup_pixmap(disp, s);
xcomp_create_pixmap(conn, s, LOG_ERROR);
xcb_xcursor_offset_win(conn, s->cursor, s->win);
xcb_xcursor_offset(s->cursor, s->cursor->x_org + s->crop_left, s->cursor->y_org + s->crop_top);
pthread_mutex_unlock(&s->lock);
obs_leave_graphics();
}
static const char *xcompcap_getname(void *data)
{
UNUSED_PARAMETER(data);
return obs_module_text("XCCapture");
}
void xcomposite_load(void)
{
disp = XOpenDisplay(NULL);
conn = XGetXCBConnection(disp);
if (xcb_connection_has_error(conn)) {
blog(LOG_ERROR, "failed opening display");
return;
}
const xcb_query_extension_reply_t *xcomp_ext = xcb_get_extension_data(conn, &xcb_composite_id);
if (!xcomp_ext->present) {
blog(LOG_ERROR, "Xcomposite extension not supported");
return;
}
xcb_composite_query_version_cookie_t version_cookie = xcb_composite_query_version(conn, 0, 2);
xcb_composite_query_version_reply_t *version = xcb_composite_query_version_reply(conn, version_cookie, NULL);
if (version->major_version == 0 && version->minor_version < 2) {
blog(LOG_ERROR, "Xcomposite extension is too old: %d.%d < 0.2", version->major_version,
version->minor_version);
free(version);
return;
}
free(version);
// Must be done before other helpers called.
xcomp_gather_atoms(conn);
xcb_screen_t *screen_default = xcb_get_screen(conn, DefaultScreen(disp));
if (!screen_default || !xcomp_check_ewmh(conn, screen_default->root)) {
blog(LOG_ERROR,
"window manager does not support Extended Window Manager Hints (EWMH).\nXComposite capture disabled.");
return;
}
struct obs_source_info sinfo = {
.id = "xcomposite_input",
.output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | OBS_SOURCE_DO_NOT_DUPLICATE,
.get_name = xcompcap_getname,
.create = xcompcap_create,
.destroy = xcompcap_destroy,
.get_properties = xcompcap_props,
.get_defaults = xcompcap_defaults,
.update = xcompcap_update,
.video_tick = xcompcap_video_tick,
.video_render = xcompcap_video_render,
.get_width = xcompcap_get_width,
.get_height = xcompcap_get_height,
.icon_type = OBS_ICON_TYPE_WINDOW_CAPTURE,
};
obs_register_source(&sinfo);
}
void xcomposite_unload(void)
{
XCloseDisplay(disp);
disp = NULL;
conn = NULL;
watcher_unload();
}
| 27,975 |
C
|
.c
| 808 | 32.096535 | 113 | 0.697344 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,476 |
v4l2-decoder.c
|
obsproject_obs-studio/plugins/linux-v4l2/v4l2-decoder.c
|
/*
Copyright (C) 2020 by Morten Bøgeskov <[email protected]>
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/>.
*/
#include <obs-module.h>
#include <linux/videodev2.h>
#include "v4l2-decoder.h"
#define blog(level, msg, ...) blog(level, "v4l2-input: decoder: " msg, ##__VA_ARGS__)
int v4l2_init_decoder(struct v4l2_decoder *decoder, int pixfmt)
{
if (pixfmt == V4L2_PIX_FMT_MJPEG) {
decoder->codec = avcodec_find_decoder(AV_CODEC_ID_MJPEG);
} else if (pixfmt == V4L2_PIX_FMT_H264) {
decoder->codec = avcodec_find_decoder(AV_CODEC_ID_H264);
}
if (!decoder->codec) {
if (pixfmt == V4L2_PIX_FMT_MJPEG) {
blog(LOG_ERROR, "failed to find MJPEG decoder");
} else if (pixfmt == V4L2_PIX_FMT_H264) {
blog(LOG_ERROR, "failed to find H264 decoder");
}
return -1;
}
decoder->context = avcodec_alloc_context3(decoder->codec);
if (!decoder->context) {
return -1;
}
decoder->packet = av_packet_alloc();
if (!decoder->packet) {
return -1;
}
decoder->frame = av_frame_alloc();
if (!decoder->frame) {
return -1;
}
decoder->context->flags2 |= AV_CODEC_FLAG2_FAST;
if (avcodec_open2(decoder->context, decoder->codec, NULL) < 0) {
blog(LOG_ERROR, "failed to open codec");
return -1;
}
blog(LOG_DEBUG, "initialized avcodec");
return 0;
}
void v4l2_destroy_decoder(struct v4l2_decoder *decoder)
{
blog(LOG_DEBUG, "destroying avcodec");
if (decoder->frame) {
av_frame_free(&decoder->frame);
}
if (decoder->packet) {
av_packet_free(&decoder->packet);
}
if (decoder->context) {
#if LIBAVCODEC_VERSION_MAJOR < 61
avcodec_close(decoder->context);
#endif
avcodec_free_context(&decoder->context);
}
}
int v4l2_decode_frame(struct obs_source_frame *out, uint8_t *data, size_t length, struct v4l2_decoder *decoder)
{
decoder->packet->data = data;
decoder->packet->size = length;
if (avcodec_send_packet(decoder->context, decoder->packet) < 0) {
blog(LOG_ERROR, "failed to send frame to codec");
return -1;
}
if (avcodec_receive_frame(decoder->context, decoder->frame) < 0) {
blog(LOG_ERROR, "failed to receive frame from codec");
return -1;
}
for (uint_fast32_t i = 0; i < MAX_AV_PLANES; ++i) {
out->data[i] = decoder->frame->data[i];
out->linesize[i] = decoder->frame->linesize[i];
}
switch (decoder->context->pix_fmt) {
case AV_PIX_FMT_GRAY8:
out->format = VIDEO_FORMAT_Y800;
break;
case AV_PIX_FMT_YUVJ422P:
case AV_PIX_FMT_YUV422P:
out->format = VIDEO_FORMAT_I422;
break;
case AV_PIX_FMT_YUVJ420P:
case AV_PIX_FMT_YUV420P:
out->format = VIDEO_FORMAT_I420;
break;
case AV_PIX_FMT_YUVJ444P:
case AV_PIX_FMT_YUV444P:
out->format = VIDEO_FORMAT_I444;
break;
default:
break;
}
return 0;
}
| 3,249 |
C
|
.c
| 105 | 28.67619 | 111 | 0.717489 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
2,483 |
v4l2-udev.c
|
obsproject_obs-studio/plugins/linux-v4l2/v4l2-udev.c
|
/*
Copyright (C) 2014 by Leonhard Oelke <[email protected]>
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/>.
*/
#include <sys/eventfd.h>
#include <poll.h>
#include <unistd.h>
#include <libudev.h>
#include <util/threading.h>
#include <util/darray.h>
#include <obs.h>
#include "v4l2-udev.h"
/** udev action enum */
enum udev_action { UDEV_ACTION_ADDED, UDEV_ACTION_REMOVED, UDEV_ACTION_UNKNOWN };
static const char *udev_signals[] = {"void device_added(string device)", "void device_removed(string device)", NULL};
/* global data */
static uint_fast32_t udev_refs = 0;
static pthread_mutex_t udev_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_t udev_thread;
static os_event_t *udev_event;
static int udev_event_fd;
static signal_handler_t *udev_signalhandler = NULL;
/**
* udev gives us the device action as string, so we convert it here ...
*
* @param action the udev action as string
* @return the udev action as enum value
*/
static enum udev_action udev_action_to_enum(const char *action)
{
if (!action)
return UDEV_ACTION_UNKNOWN;
if (!strncmp("add", action, 3))
return UDEV_ACTION_ADDED;
if (!strncmp("remove", action, 6))
return UDEV_ACTION_REMOVED;
return UDEV_ACTION_UNKNOWN;
}
/**
* Call all registered callbacks with the event
*
* @param dev udev device that had an event occuring
*/
static inline void udev_signal_event(struct udev_device *dev)
{
const char *node;
enum udev_action action;
struct calldata data;
pthread_mutex_lock(&udev_mutex);
node = udev_device_get_devnode(dev);
action = udev_action_to_enum(udev_device_get_action(dev));
calldata_init(&data);
calldata_set_string(&data, "device", node);
switch (action) {
case UDEV_ACTION_ADDED:
signal_handler_signal(udev_signalhandler, "device_added", &data);
break;
case UDEV_ACTION_REMOVED:
signal_handler_signal(udev_signalhandler, "device_removed", &data);
break;
default:
break;
}
calldata_free(&data);
pthread_mutex_unlock(&udev_mutex);
}
/**
* Event listener thread
*/
static void *udev_event_thread(void *vptr)
{
UNUSED_PARAMETER(vptr);
int fd;
struct udev *udev;
struct udev_monitor *mon;
struct udev_device *dev;
/* set up udev monitoring */
os_set_thread_name("v4l2: udev");
udev = udev_new();
mon = udev_monitor_new_from_netlink(udev, "udev");
udev_monitor_filter_add_match_subsystem_devtype(mon, "video4linux", NULL);
if (udev_monitor_enable_receiving(mon) < 0)
return NULL;
/* set up fds */
fd = udev_monitor_get_fd(mon);
while (os_event_try(udev_event) == EAGAIN) {
struct pollfd fds[2];
fds[0].fd = fd;
fds[0].events = POLLIN;
fds[0].revents = 0;
fds[1].fd = udev_event_fd;
fds[1].events = POLLIN;
if (poll(fds, 2, 1000) <= 0)
continue;
if (!(fds[0].revents & POLLIN))
continue;
dev = udev_monitor_receive_device(mon);
if (!dev)
continue;
udev_signal_event(dev);
udev_device_unref(dev);
}
udev_monitor_unref(mon);
udev_unref(udev);
return NULL;
}
void v4l2_init_udev(void)
{
pthread_mutex_lock(&udev_mutex);
/* set up udev */
if (udev_refs == 0) {
if (os_event_init(&udev_event, OS_EVENT_TYPE_MANUAL) != 0)
goto fail;
if ((udev_event_fd = eventfd(0, EFD_CLOEXEC)) < 0)
goto fail;
if (pthread_create(&udev_thread, NULL, udev_event_thread, NULL) != 0) {
close(udev_event_fd);
goto fail;
}
udev_signalhandler = signal_handler_create();
if (!udev_signalhandler) {
close(udev_event_fd);
goto fail;
}
signal_handler_add_array(udev_signalhandler, udev_signals);
}
udev_refs++;
fail:
pthread_mutex_unlock(&udev_mutex);
}
void v4l2_unref_udev(void)
{
pthread_mutex_lock(&udev_mutex);
/* unref udev monitor */
if (udev_refs && --udev_refs == 0) {
os_event_signal(udev_event);
eventfd_write(udev_event_fd, 1);
pthread_join(udev_thread, NULL);
os_event_destroy(udev_event);
close(udev_event_fd);
if (udev_signalhandler)
signal_handler_destroy(udev_signalhandler);
udev_signalhandler = NULL;
}
pthread_mutex_unlock(&udev_mutex);
}
signal_handler_t *v4l2_get_udev_signalhandler(void)
{
return udev_signalhandler;
}
| 4,657 |
C
|
.c
| 159 | 26.993711 | 117 | 0.729457 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,489 |
obs-ffmpeg-av1.c
|
obsproject_obs-studio/plugins/obs-ffmpeg/obs-ffmpeg-av1.c
|
/******************************************************************************
Copyright (C) 2023 by Lain Bailey <[email protected]>
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/>.
******************************************************************************/
#include "obs-ffmpeg-video-encoders.h"
#define do_log(level, format, ...) \
blog(level, "[AV1 encoder: '%s'] " format, obs_encoder_get_name(enc->ffve.encoder), ##__VA_ARGS__)
#define error(format, ...) do_log(LOG_ERROR, format, ##__VA_ARGS__)
#define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
#define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
#define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
enum av1_encoder_type {
AV1_ENCODER_TYPE_AOM,
AV1_ENCODER_TYPE_SVT,
};
struct av1_encoder {
struct ffmpeg_video_encoder ffve;
enum av1_encoder_type type;
DARRAY(uint8_t) header;
};
static const char *aom_av1_getname(void *unused)
{
UNUSED_PARAMETER(unused);
return "AOM AV1";
}
static const char *svt_av1_getname(void *unused)
{
UNUSED_PARAMETER(unused);
return "SVT-AV1";
}
static void av1_video_info(void *data, struct video_scale_info *info)
{
UNUSED_PARAMETER(data);
switch (info->format) {
case VIDEO_FORMAT_I010:
case VIDEO_FORMAT_P010:
info->format = VIDEO_FORMAT_I010;
break;
default:
info->format = VIDEO_FORMAT_I420;
}
}
static bool av1_update(struct av1_encoder *enc, obs_data_t *settings)
{
const char *rc = obs_data_get_string(settings, "rate_control");
int bitrate = (int)obs_data_get_int(settings, "bitrate");
int cqp = (int)obs_data_get_int(settings, "cqp");
int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec");
int preset = (int)obs_data_get_int(settings, "preset");
AVDictionary *svtav1_opts = NULL;
video_t *video = obs_encoder_video(enc->ffve.encoder);
const struct video_output_info *voi = video_output_get_info(video);
struct video_scale_info info;
info.format = voi->format;
info.colorspace = voi->colorspace;
info.range = voi->range;
enc->ffve.context->thread_count = 0;
av1_video_info(enc, &info);
if (enc->type == AV1_ENCODER_TYPE_SVT) {
av_opt_set_int(enc->ffve.context->priv_data, "preset", preset, 0);
av_dict_set_int(&svtav1_opts, "rc", 1, 0);
} else if (enc->type == AV1_ENCODER_TYPE_AOM) {
av_opt_set_int(enc->ffve.context->priv_data, "cpu-used", preset, 0);
av_opt_set(enc->ffve.context->priv_data, "usage", "realtime", 0);
#if 0
av_opt_set_int(enc->ffve.context->priv_data, "tile-columns", 4, 0);
//av_opt_set_int(enc->ffve.context->priv_data, "tile-rows", 4, 0);
#else
av_opt_set_int(enc->ffve.context->priv_data, "tile-columns", 2, 0);
av_opt_set_int(enc->ffve.context->priv_data, "tile-rows", 2, 0);
#endif
av_opt_set_int(enc->ffve.context->priv_data, "row-mt", 1, 0);
}
if (astrcmpi(rc, "cqp") == 0) {
bitrate = 0;
av_opt_set_int(enc->ffve.context->priv_data, "crf", cqp, 0);
if (enc->type == AV1_ENCODER_TYPE_SVT) {
av_dict_set_int(&svtav1_opts, "rc", 0, 0);
av_opt_set_int(enc->ffve.context->priv_data, "qp", cqp, 0);
}
} else if (astrcmpi(rc, "vbr") != 0) { /* CBR by default */
const int64_t rate = bitrate * INT64_C(1000);
enc->ffve.context->rc_min_rate = rate;
cqp = 0;
if (enc->type == AV1_ENCODER_TYPE_SVT) {
av_dict_set_int(&svtav1_opts, "rc", 2, 0);
av_dict_set_int(&svtav1_opts, "pred-struct", 1, 0);
av_dict_set_int(&svtav1_opts, "bias-pct", 0, 0);
av_dict_set_int(&svtav1_opts, "tbr", rate, 0);
} else {
enc->ffve.context->rc_max_rate = rate;
}
}
if (enc->type == AV1_ENCODER_TYPE_SVT) {
av_opt_set_dict_val(enc->ffve.context->priv_data, "svtav1_opts", svtav1_opts, 0);
}
const char *ffmpeg_opts = obs_data_get_string(settings, "ffmpeg_opts");
ffmpeg_video_encoder_update(&enc->ffve, bitrate, keyint_sec, voi, &info, ffmpeg_opts);
av_dict_free(&svtav1_opts);
info("settings:\n"
"\tencoder: %s\n"
"\trate_control: %s\n"
"\tbitrate: %d\n"
"\tcqp: %d\n"
"\tkeyint: %d\n"
"\tpreset: %d\n"
"\twidth: %d\n"
"\theight: %d\n"
"\tffmpeg opts: %s\n",
enc->ffve.enc_name, rc, bitrate, cqp, enc->ffve.context->gop_size, preset, enc->ffve.context->width,
enc->ffve.height, ffmpeg_opts);
enc->ffve.context->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
return ffmpeg_video_encoder_init_codec(&enc->ffve);
}
static void av1_destroy(void *data)
{
struct av1_encoder *enc = data;
ffmpeg_video_encoder_free(&enc->ffve);
da_free(enc->header);
bfree(enc);
}
static void on_first_packet(void *data, AVPacket *pkt, struct darray *da)
{
struct av1_encoder *enc = data;
if (enc->type == AV1_ENCODER_TYPE_SVT) {
da_copy_array(enc->header, enc->ffve.context->extradata, enc->ffve.context->extradata_size);
} else {
for (int i = 0; i < pkt->side_data_elems; i++) {
AVPacketSideData *side_data = pkt->side_data + i;
if (side_data->type == AV_PKT_DATA_NEW_EXTRADATA) {
da_copy_array(enc->header, side_data->data, side_data->size);
break;
}
}
}
darray_copy_array(1, da, pkt->data, pkt->size);
}
static void *av1_create_internal(obs_data_t *settings, obs_encoder_t *encoder, const char *enc_lib,
const char *enc_name)
{
video_t *video = obs_encoder_video(encoder);
const struct video_output_info *voi = video_output_get_info(video);
if (voi->format != VIDEO_FORMAT_P010 && voi->format != VIDEO_FORMAT_I010) {
if (voi->colorspace == VIDEO_CS_2100_PQ || voi->colorspace == VIDEO_CS_2100_HLG) {
const char *const text = obs_module_text("AV1.8bitUnsupportedHdr");
obs_encoder_set_last_error(encoder, text);
blog(LOG_ERROR, "[AV1 encoder] %s", text);
return NULL;
}
}
struct av1_encoder *enc = bzalloc(sizeof(*enc));
if (strcmp(enc_lib, "libsvtav1") == 0)
enc->type = AV1_ENCODER_TYPE_SVT;
else if (strcmp(enc_lib, "libaom-av1") == 0)
enc->type = AV1_ENCODER_TYPE_AOM;
if (!ffmpeg_video_encoder_init(&enc->ffve, enc, encoder, enc_lib, NULL, enc_name, NULL, on_first_packet))
goto fail;
if (!av1_update(enc, settings))
goto fail;
return enc;
fail:
av1_destroy(enc);
return NULL;
}
static void *svt_av1_create(obs_data_t *settings, obs_encoder_t *encoder)
{
return av1_create_internal(settings, encoder, "libsvtav1", "SVT-AV1");
}
static void *aom_av1_create(obs_data_t *settings, obs_encoder_t *encoder)
{
return av1_create_internal(settings, encoder, "libaom-av1", "AOM AV1");
}
static bool av1_encode(void *data, struct encoder_frame *frame, struct encoder_packet *packet, bool *received_packet)
{
struct av1_encoder *enc = data;
return ffmpeg_video_encode(&enc->ffve, frame, packet, received_packet);
}
void av1_defaults(obs_data_t *settings)
{
obs_data_set_default_int(settings, "bitrate", 2500);
obs_data_set_default_int(settings, "keyint_sec", 0);
obs_data_set_default_int(settings, "cqp", 50);
obs_data_set_default_string(settings, "rate_control", "CBR");
obs_data_set_default_int(settings, "preset", 8);
}
static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p, obs_data_t *settings)
{
const char *rc = obs_data_get_string(settings, "rate_control");
bool cqp = astrcmpi(rc, "CQP") == 0;
bool vbr = astrcmpi(rc, "VBR") == 0;
p = obs_properties_get(ppts, "bitrate");
obs_property_set_visible(p, !cqp);
p = obs_properties_get(ppts, "max_bitrate");
obs_property_set_visible(p, vbr);
p = obs_properties_get(ppts, "cqp");
obs_property_set_visible(p, cqp);
return true;
}
obs_properties_t *av1_properties(enum av1_encoder_type type)
{
obs_properties_t *props = obs_properties_create();
obs_property_t *p;
p = obs_properties_add_list(props, "rate_control", obs_module_text("RateControl"), OBS_COMBO_TYPE_LIST,
OBS_COMBO_FORMAT_STRING);
obs_property_list_add_string(p, "CBR", "CBR");
obs_property_list_add_string(p, "CQP", "CQP");
obs_property_list_add_string(p, "VBR", "VBR");
obs_property_set_modified_callback(p, rate_control_modified);
p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), 50, 300000, 50);
obs_property_int_set_suffix(p, " Kbps");
obs_properties_add_int(props, "cqp", obs_module_text("NVENC.CQLevel"), 1, 63, 1);
p = obs_properties_add_int(props, "keyint_sec", obs_module_text("KeyframeIntervalSec"), 0, 10, 1);
obs_property_int_set_suffix(p, " s");
p = obs_properties_add_list(props, "preset", obs_module_text("Preset"), OBS_COMBO_TYPE_LIST,
OBS_COMBO_FORMAT_INT);
if (type == AV1_ENCODER_TYPE_SVT) {
obs_property_list_add_int(p, "Very likely too slow (6)", 6);
obs_property_list_add_int(p, "Probably too slow (7)", 7);
obs_property_list_add_int(p, "Seems okay (8)", 8);
obs_property_list_add_int(p, "Might be better (9)", 9);
obs_property_list_add_int(p, "A little bit faster? (10)", 10);
obs_property_list_add_int(p, "Hmm, not bad speed (11)", 11);
obs_property_list_add_int(p, "Whoa, although quality might be not so great (12)", 12);
} else if (type == AV1_ENCODER_TYPE_AOM) {
obs_property_list_add_int(p, "Probably too slow (7)", 7);
obs_property_list_add_int(p, "Okay (8)", 8);
obs_property_list_add_int(p, "Fast (9)", 9);
obs_property_list_add_int(p, "Fastest (10)", 10);
}
obs_properties_add_text(props, "ffmpeg_opts", obs_module_text("FFmpegOpts"), OBS_TEXT_DEFAULT);
return props;
}
obs_properties_t *aom_av1_properties(void *unused)
{
UNUSED_PARAMETER(unused);
return av1_properties(AV1_ENCODER_TYPE_AOM);
}
obs_properties_t *svt_av1_properties(void *unused)
{
UNUSED_PARAMETER(unused);
return av1_properties(AV1_ENCODER_TYPE_SVT);
}
static bool av1_extra_data(void *data, uint8_t **extra_data, size_t *size)
{
struct av1_encoder *enc = data;
*extra_data = enc->header.array;
*size = enc->header.num;
return true;
}
struct obs_encoder_info svt_av1_encoder_info = {
.id = "ffmpeg_svt_av1",
.type = OBS_ENCODER_VIDEO,
.codec = "av1",
.get_name = svt_av1_getname,
.create = svt_av1_create,
.destroy = av1_destroy,
.encode = av1_encode,
.get_defaults = av1_defaults,
.get_properties = svt_av1_properties,
.get_extra_data = av1_extra_data,
.get_video_info = av1_video_info,
};
struct obs_encoder_info aom_av1_encoder_info = {
.id = "ffmpeg_aom_av1",
.type = OBS_ENCODER_VIDEO,
.codec = "av1",
.get_name = aom_av1_getname,
.create = aom_av1_create,
.destroy = av1_destroy,
.encode = av1_encode,
.get_defaults = av1_defaults,
.get_properties = aom_av1_properties,
.get_extra_data = av1_extra_data,
.get_video_info = av1_video_info,
};
| 11,095 |
C
|
.c
| 284 | 36.443662 | 117 | 0.67783 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,490 |
obs-ffmpeg-audio-encoders.c
|
obsproject_obs-studio/plugins/obs-ffmpeg/obs-ffmpeg-audio-encoders.c
|
/******************************************************************************
Copyright (C) 2023 by Lain Bailey <[email protected]>
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/>.
******************************************************************************/
#include <util/base.h>
#include <util/deque.h>
#include <util/darray.h>
#include <util/dstr.h>
#include <obs-module.h>
#include <libavutil/channel_layout.h>
#include <libavformat/avformat.h>
#include "obs-ffmpeg-formats.h"
#include "obs-ffmpeg-compat.h"
#define do_log(level, format, ...) \
blog(level, "[FFmpeg %s encoder: '%s'] " format, enc->type, obs_encoder_get_name(enc->encoder), ##__VA_ARGS__)
#define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
#define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
#define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
struct enc_encoder {
obs_encoder_t *encoder;
const char *type;
const AVCodec *codec;
AVCodecContext *context;
uint8_t *samples[MAX_AV_PLANES];
AVFrame *aframe;
int64_t total_samples;
DARRAY(uint8_t) packet_buffer;
size_t audio_planes;
size_t audio_size;
int frame_size; /* pretty much always 1024 for AAC */
int frame_size_bytes;
};
static const char *aac_getname(void *unused)
{
UNUSED_PARAMETER(unused);
return obs_module_text("FFmpegAAC");
}
static const char *opus_getname(void *unused)
{
UNUSED_PARAMETER(unused);
return obs_module_text("FFmpegOpus");
}
static const char *pcm_getname(void *unused)
{
UNUSED_PARAMETER(unused);
return obs_module_text("FFmpegPCM16Bit");
}
static const char *pcm24_getname(void *unused)
{
UNUSED_PARAMETER(unused);
return obs_module_text("FFmpegPCM24Bit");
}
static const char *pcm32_getname(void *unused)
{
UNUSED_PARAMETER(unused);
return obs_module_text("FFmpegPCM32BitFloat");
}
static const char *alac_getname(void *unused)
{
UNUSED_PARAMETER(unused);
return obs_module_text("FFmpegALAC");
}
static const char *flac_getname(void *unused)
{
UNUSED_PARAMETER(unused);
return obs_module_text("FFmpegFLAC");
}
static void enc_destroy(void *data)
{
struct enc_encoder *enc = data;
if (enc->samples[0])
av_freep(&enc->samples[0]);
if (enc->context)
avcodec_free_context(&enc->context);
if (enc->aframe)
av_frame_free(&enc->aframe);
da_free(enc->packet_buffer);
bfree(enc);
}
static bool initialize_codec(struct enc_encoder *enc)
{
int ret;
int channels;
enc->aframe = av_frame_alloc();
if (!enc->aframe) {
warn("Failed to allocate audio frame");
return false;
}
ret = avcodec_open2(enc->context, enc->codec, NULL);
if (ret < 0) {
struct dstr error_message = {0};
dstr_printf(&error_message, "Failed to open AAC codec: %s", av_err2str(ret));
obs_encoder_set_last_error(enc->encoder, error_message.array);
dstr_free(&error_message);
warn("Failed to open AAC codec: %s", av_err2str(ret));
return false;
}
enc->aframe->format = enc->context->sample_fmt;
channels = enc->context->ch_layout.nb_channels;
enc->aframe->ch_layout = enc->context->ch_layout;
enc->aframe->sample_rate = enc->context->sample_rate;
enc->frame_size = enc->context->frame_size;
if (!enc->frame_size)
enc->frame_size = 1024;
enc->frame_size_bytes = enc->frame_size * (int)enc->audio_size;
ret = av_samples_alloc(enc->samples, NULL, channels, enc->frame_size, enc->context->sample_fmt, 0);
if (ret < 0) {
warn("Failed to create audio buffer: %s", av_err2str(ret));
return false;
}
return true;
}
static void init_sizes(struct enc_encoder *enc, audio_t *audio)
{
const struct audio_output_info *aoi;
enum audio_format format;
aoi = audio_output_get_info(audio);
format = convert_ffmpeg_sample_format(enc->context->sample_fmt);
enc->audio_planes = get_audio_planes(format, aoi->speakers);
enc->audio_size = get_audio_size(format, aoi->speakers, 1);
}
#ifndef MIN
#define MIN(x, y) ((x) < (y) ? (x) : (y))
#endif
static void *enc_create(obs_data_t *settings, obs_encoder_t *encoder, const char *type, const char *alt,
enum AVSampleFormat sample_format)
{
struct enc_encoder *enc;
int bitrate = (int)obs_data_get_int(settings, "bitrate");
audio_t *audio = obs_encoder_audio(encoder);
enc = bzalloc(sizeof(struct enc_encoder));
enc->encoder = encoder;
enc->codec = avcodec_find_encoder_by_name(type);
enc->type = type;
if (!enc->codec && alt) {
enc->codec = avcodec_find_encoder_by_name(alt);
enc->type = alt;
}
blog(LOG_INFO, "---------------------------------");
if (!enc->codec) {
warn("Couldn't find encoder");
goto fail;
}
const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(enc->codec->id);
if (!codec_desc) {
warn("Failed to get codec descriptor");
goto fail;
}
if (!bitrate && !(codec_desc->props & AV_CODEC_PROP_LOSSLESS)) {
warn("Invalid bitrate specified");
goto fail;
}
enc->context = avcodec_alloc_context3(enc->codec);
if (!enc->context) {
warn("Failed to create codec context");
goto fail;
}
if (codec_desc->props & AV_CODEC_PROP_LOSSLESS)
// Set by encoder on init, not known at this time
enc->context->bit_rate = -1;
else
enc->context->bit_rate = bitrate * 1000;
const struct audio_output_info *aoi;
aoi = audio_output_get_info(audio);
av_channel_layout_default(&enc->context->ch_layout, (int)audio_output_get_channels(audio));
/* The avutil default channel layout for 5 channels is 5.0, which OBS
* does not support. Manually set 5 channels to 4.1. */
if (aoi->speakers == SPEAKERS_4POINT1)
enc->context->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_4POINT1;
/* AAC, ALAC, & FLAC default to 3.0 for 3 channels instead of 2.1.
* Tell the encoder to deal with 2.1 as if it were 3.0. */
if (aoi->speakers == SPEAKERS_2POINT1)
enc->context->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_SURROUND;
// ALAC supports 7.1 wide instead of regular 7.1.
if (aoi->speakers == SPEAKERS_7POINT1 && astrcmpi(enc->type, "alac") == 0)
enc->context->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_7POINT1_WIDE_BACK;
enc->context->sample_rate = audio_output_get_sample_rate(audio);
if (enc->codec->sample_fmts) {
/* Check if the requested format is actually available for the specified
* encoder. This may not always be the case due to FFmpeg changes or a
* fallback being used (for example, when libopus is unavailable). */
const enum AVSampleFormat *fmt = enc->codec->sample_fmts;
while (*fmt != AV_SAMPLE_FMT_NONE) {
if (*fmt == sample_format) {
enc->context->sample_fmt = *fmt;
break;
}
fmt++;
}
/* Fall back to default if requested format was not found. */
if (enc->context->sample_fmt == AV_SAMPLE_FMT_NONE)
enc->context->sample_fmt = enc->codec->sample_fmts[0];
} else {
/* Fall back to planar float if codec does not specify formats. */
enc->context->sample_fmt = AV_SAMPLE_FMT_FLTP;
}
/* check to make sure sample rate is supported */
if (enc->codec->supported_samplerates) {
const int *rate = enc->codec->supported_samplerates;
int cur_rate = enc->context->sample_rate;
int closest = 0;
while (*rate) {
int dist = abs(cur_rate - *rate);
int closest_dist = abs(cur_rate - closest);
if (dist < closest_dist)
closest = *rate;
rate++;
}
if (closest)
enc->context->sample_rate = closest;
}
char buf[256];
av_channel_layout_describe(&enc->context->ch_layout, buf, 256);
info("bitrate: %" PRId64 ", channels: %d, channel_layout: %s, track: %d\n",
(int64_t)enc->context->bit_rate / 1000, (int)enc->context->ch_layout.nb_channels, buf,
(int)obs_encoder_get_mixer_index(enc->encoder) + 1);
init_sizes(enc, audio);
/* enable experimental FFmpeg encoder if the only one available */
enc->context->strict_std_compliance = -2;
enc->context->flags = AV_CODEC_FLAG_GLOBAL_HEADER;
if (initialize_codec(enc))
return enc;
fail:
enc_destroy(enc);
return NULL;
}
static void *aac_create(obs_data_t *settings, obs_encoder_t *encoder)
{
return enc_create(settings, encoder, "aac", NULL, AV_SAMPLE_FMT_NONE);
}
static void *opus_create(obs_data_t *settings, obs_encoder_t *encoder)
{
return enc_create(settings, encoder, "libopus", "opus", AV_SAMPLE_FMT_FLT);
}
static void *pcm_create(obs_data_t *settings, obs_encoder_t *encoder)
{
return enc_create(settings, encoder, "pcm_s16le", NULL, AV_SAMPLE_FMT_NONE);
}
static void *pcm24_create(obs_data_t *settings, obs_encoder_t *encoder)
{
return enc_create(settings, encoder, "pcm_s24le", NULL, AV_SAMPLE_FMT_NONE);
}
static void *pcm32_create(obs_data_t *settings, obs_encoder_t *encoder)
{
return enc_create(settings, encoder, "pcm_f32le", NULL, AV_SAMPLE_FMT_NONE);
}
static void *alac_create(obs_data_t *settings, obs_encoder_t *encoder)
{
return enc_create(settings, encoder, "alac", NULL, AV_SAMPLE_FMT_S32P);
}
static void *flac_create(obs_data_t *settings, obs_encoder_t *encoder)
{
return enc_create(settings, encoder, "flac", NULL, AV_SAMPLE_FMT_S16);
}
static bool do_encode(struct enc_encoder *enc, struct encoder_packet *packet, bool *received_packet)
{
AVRational time_base = {1, enc->context->sample_rate};
AVPacket avpacket = {0};
int got_packet;
int ret;
int channels;
enc->aframe->nb_samples = enc->frame_size;
enc->aframe->pts =
av_rescale_q(enc->total_samples, (AVRational){1, enc->context->sample_rate}, enc->context->time_base);
enc->aframe->ch_layout = enc->context->ch_layout;
channels = enc->context->ch_layout.nb_channels;
ret = avcodec_fill_audio_frame(enc->aframe, channels, enc->context->sample_fmt, enc->samples[0],
enc->frame_size_bytes * channels, 1);
if (ret < 0) {
warn("avcodec_fill_audio_frame failed: %s", av_err2str(ret));
return false;
}
enc->total_samples += enc->frame_size;
ret = avcodec_send_frame(enc->context, enc->aframe);
if (ret == 0)
ret = avcodec_receive_packet(enc->context, &avpacket);
got_packet = (ret == 0);
if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
ret = 0;
if (ret < 0) {
warn("avcodec_encode_audio2 failed: %s", av_err2str(ret));
return false;
}
*received_packet = !!got_packet;
if (!got_packet)
return true;
da_resize(enc->packet_buffer, 0);
da_push_back_array(enc->packet_buffer, avpacket.data, avpacket.size);
packet->pts = rescale_ts(avpacket.pts, enc->context, time_base);
packet->dts = rescale_ts(avpacket.dts, enc->context, time_base);
packet->data = enc->packet_buffer.array;
packet->size = avpacket.size;
packet->type = OBS_ENCODER_AUDIO;
packet->keyframe = true;
packet->timebase_num = 1;
packet->timebase_den = (int32_t)enc->context->sample_rate;
av_packet_unref(&avpacket);
return true;
}
static bool enc_encode(void *data, struct encoder_frame *frame, struct encoder_packet *packet, bool *received_packet)
{
struct enc_encoder *enc = data;
for (size_t i = 0; i < enc->audio_planes; i++)
memcpy(enc->samples[i], frame->data[i], enc->frame_size_bytes);
return do_encode(enc, packet, received_packet);
}
static void enc_defaults(obs_data_t *settings)
{
obs_data_set_default_int(settings, "bitrate", 128);
}
static obs_properties_t *enc_properties(void *unused)
{
UNUSED_PARAMETER(unused);
obs_properties_t *props = obs_properties_create();
obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), 64, 1024, 32);
return props;
}
static bool enc_extra_data(void *data, uint8_t **extra_data, size_t *size)
{
struct enc_encoder *enc = data;
*extra_data = enc->context->extradata;
*size = enc->context->extradata_size;
return true;
}
static void enc_audio_info(void *data, struct audio_convert_info *info)
{
struct enc_encoder *enc = data;
int channels;
channels = enc->context->ch_layout.nb_channels;
info->format = convert_ffmpeg_sample_format(enc->context->sample_fmt);
info->samples_per_sec = (uint32_t)enc->context->sample_rate;
if (channels != 7 && channels <= 8)
info->speakers = (enum speaker_layout)(channels);
else
info->speakers = SPEAKERS_UNKNOWN;
}
static void enc_audio_info_float(void *data, struct audio_convert_info *info)
{
enc_audio_info(data, info);
info->allow_clipping = true;
}
static size_t enc_frame_size(void *data)
{
struct enc_encoder *enc = data;
return enc->frame_size;
}
struct obs_encoder_info aac_encoder_info = {
.id = "ffmpeg_aac",
.type = OBS_ENCODER_AUDIO,
.codec = "aac",
.get_name = aac_getname,
.create = aac_create,
.destroy = enc_destroy,
.encode = enc_encode,
.get_frame_size = enc_frame_size,
.get_defaults = enc_defaults,
.get_properties = enc_properties,
.get_extra_data = enc_extra_data,
.get_audio_info = enc_audio_info,
};
struct obs_encoder_info opus_encoder_info = {
.id = "ffmpeg_opus",
.type = OBS_ENCODER_AUDIO,
.codec = "opus",
.get_name = opus_getname,
.create = opus_create,
.destroy = enc_destroy,
.encode = enc_encode,
.get_frame_size = enc_frame_size,
.get_defaults = enc_defaults,
.get_properties = enc_properties,
.get_extra_data = enc_extra_data,
.get_audio_info = enc_audio_info,
};
struct obs_encoder_info pcm_encoder_info = {
.id = "ffmpeg_pcm_s16le",
.type = OBS_ENCODER_AUDIO,
.codec = "pcm_s16le",
.get_name = pcm_getname,
.create = pcm_create,
.destroy = enc_destroy,
.encode = enc_encode,
.get_frame_size = enc_frame_size,
.get_defaults = enc_defaults,
.get_properties = enc_properties,
.get_extra_data = enc_extra_data,
.get_audio_info = enc_audio_info,
};
struct obs_encoder_info pcm24_encoder_info = {
.id = "ffmpeg_pcm_s24le",
.type = OBS_ENCODER_AUDIO,
.codec = "pcm_s24le",
.get_name = pcm24_getname,
.create = pcm24_create,
.destroy = enc_destroy,
.encode = enc_encode,
.get_frame_size = enc_frame_size,
.get_defaults = enc_defaults,
.get_properties = enc_properties,
.get_extra_data = enc_extra_data,
.get_audio_info = enc_audio_info,
};
struct obs_encoder_info pcm32_encoder_info = {
.id = "ffmpeg_pcm_f32le",
.type = OBS_ENCODER_AUDIO,
.codec = "pcm_f32le",
.get_name = pcm32_getname,
.create = pcm32_create,
.destroy = enc_destroy,
.encode = enc_encode,
.get_frame_size = enc_frame_size,
.get_defaults = enc_defaults,
.get_properties = enc_properties,
.get_extra_data = enc_extra_data,
.get_audio_info = enc_audio_info_float,
};
struct obs_encoder_info alac_encoder_info = {
.id = "ffmpeg_alac",
.type = OBS_ENCODER_AUDIO,
.codec = "alac",
.get_name = alac_getname,
.create = alac_create,
.destroy = enc_destroy,
.encode = enc_encode,
.get_frame_size = enc_frame_size,
.get_defaults = enc_defaults,
.get_properties = enc_properties,
.get_extra_data = enc_extra_data,
.get_audio_info = enc_audio_info,
};
struct obs_encoder_info flac_encoder_info = {
.id = "ffmpeg_flac",
.type = OBS_ENCODER_AUDIO,
.codec = "flac",
.get_name = flac_getname,
.create = flac_create,
.destroy = enc_destroy,
.encode = enc_encode,
.get_frame_size = enc_frame_size,
.get_defaults = enc_defaults,
.get_properties = enc_properties,
.get_extra_data = enc_extra_data,
.get_audio_info = enc_audio_info,
};
| 15,496 |
C
|
.c
| 453 | 31.927152 | 117 | 0.703686 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,494 |
obs-ffmpeg-video-encoders.h
|
obsproject_obs-studio/plugins/obs-ffmpeg/obs-ffmpeg-video-encoders.h
|
#pragma once
#include <util/platform.h>
#include <util/darray.h>
#include <util/dstr.h>
#include <util/base.h>
#include <media-io/video-io.h>
#include <opts-parser.h>
#include <obs-module.h>
#include <libavutil/opt.h>
#include <libavutil/pixdesc.h>
#include <libavformat/avformat.h>
#include "obs-ffmpeg-formats.h"
typedef void (*init_error_cb)(void *data, int ret);
typedef void (*first_packet_cb)(void *data, AVPacket *pkt, struct darray *out);
struct ffmpeg_video_encoder {
obs_encoder_t *encoder;
const char *enc_name;
const AVCodec *avcodec;
AVCodecContext *context;
int64_t start_ts;
bool first_packet;
AVFrame *vframe;
DARRAY(uint8_t) buffer;
int height;
bool initialized;
void *parent;
init_error_cb on_init_error;
first_packet_cb on_first_packet;
};
extern bool ffmpeg_video_encoder_init(struct ffmpeg_video_encoder *enc, void *parent, obs_encoder_t *encoder,
const char *enc_lib, const char *enc_lib2, const char *enc_name,
init_error_cb on_init_error, first_packet_cb on_first_packet);
extern void ffmpeg_video_encoder_free(struct ffmpeg_video_encoder *enc);
extern bool ffmpeg_video_encoder_init_codec(struct ffmpeg_video_encoder *enc);
extern void ffmpeg_video_encoder_update(struct ffmpeg_video_encoder *enc, int bitrate, int keyint_sec,
const struct video_output_info *voi, const struct video_scale_info *info,
const char *ffmpeg_opts);
extern bool ffmpeg_video_encode(struct ffmpeg_video_encoder *enc, struct encoder_frame *frame,
struct encoder_packet *packet, bool *received_packet);
| 1,560 |
C
|
.c
| 39 | 37.512821 | 109 | 0.761589 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.