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
14,882,672
ut_cortxfs_link_ops.c
Seagate_cortx-fs/src/test/ut/ut_cortxfs_link_ops.c
/* * Filename: ut_cortxfs_link_ops.c * Description: Implementation tests for links * * Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * For any questions about this software or licensing, * please email [email protected] or [email protected]. */ #include "ut_cortxfs_helper.h" #define LINK_ENV_FROM_STATE(__state) (*((struct ut_link_env **)__state)) struct ut_link_env { struct ut_cfs_params ut_cfs_obj; char * link_name; }; /** * Teardown for symlink test * Description: delete a symlink with ordinary contents. * Strategy: * 1. Destroy symlink . * Expected behavior: * 1. No errors from CORTXFS API. * 2. Symlink deletion should be successful. */ static int symlink_teardown(void **state) { int rc = 0; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); ut_cfs_obj->parent_inode = CFS_ROOT_INODE; rc = ut_file_delete(state); ut_assert_int_equal(rc, 0); return rc; } /** * Test for symlink creation * Description: create a symlink with ordinary contents. * Strategy: * 1. Create a symlink with contents. * 2. Read the symlink contents. * 3. Verify the output against readlink. * Expected behavior: * 1. No errors from CORTXFS API. * 2. The symlink contents matches the input. */ static void create_symlink(void **state) { int rc = 0; char *link_name = "test_symlink", *symlink_content = "abcdefghijklmnopqrstuvwxyz"; cfs_ino_t link_inode = 0LL; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); ut_cfs_obj->file_name = link_name; rc = cfs_symlink(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->current_inode, link_name, symlink_content, &link_inode); ut_assert_int_equal(rc, 0); char buff[100]; size_t content_size = 100; rc = cfs_readlink(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &link_inode, buff, &content_size); ut_assert_int_equal(rc, 0); ut_assert_int_equal(content_size, strlen(symlink_content)); rc = memcmp(buff, symlink_content, strlen(symlink_content)); ut_assert_int_equal(rc, 0); } /** * Test for longname symlink creation * Description: create a symlink with long name with ordinary contents. * Strategy: * 1. Create a long name symlink with contents. * 2. Read the symlink contents. * 3. Verify the output against readlink. * Expected behavior: * 1. No errors from CORTXFS API * 2. The symlink contents matches the input. */ static void create_longname255_symlink(void **state) { int rc = 0; char *long_name = "123456789012345678901234567890123456789012345678901" "123456789012345678901234567890123456789012345678901" "123456789012345678901234567890123456789012345678901" "123456789012345678901234567890123456789012345678901" "123456789012345678901234567890123456789012345678901", *symlink_content = "abcdefghijklmnopqrstuvwxyz"; cfs_ino_t link_inode = 0LL; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); ut_cfs_obj->file_name = long_name; ut_assert_int_equal(255, strlen(long_name)); rc = cfs_symlink(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->current_inode, long_name, symlink_content, &link_inode); ut_assert_int_equal(rc, 0); char buff[100]; size_t content_size = 100; rc = cfs_readlink(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &link_inode, buff, &content_size); ut_assert_int_equal(rc, 0); ut_assert_int_equal(content_size, strlen(symlink_content)); rc = memcmp(buff, symlink_content, strlen(symlink_content)); ut_assert_int_equal(rc, 0); } /** * Setup for hardlink test * Description: Create a file * Strategy: * 1. Create file * Expcted behavior: * 1. No errors from CORTXFS API. * 2. File creation should be successful */ static int hardlink_setup(void **state) { int rc = 0; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); ut_cfs_obj->file_inode = 0LL; ut_cfs_obj->file_name = "test_hardlink_file"; rc = ut_file_create(state); ut_assert_int_equal(rc, 0); return rc; } /** * Teardown for hardlink test * Description: Create a file * Strategy: * 1. Delete file if not deleted * 2. Delete link if not deleted. * Expcted behavior: * 1. No errors from CORTXFS API. * 2. File and link deletion should be successful if exists */ static int hardlink_teardown(void **state) { int rc = 0; struct ut_link_env *ut_link_obj = LINK_ENV_FROM_STATE(state); ut_link_obj->ut_cfs_obj.file_inode = 0LL; if(ut_link_obj->ut_cfs_obj.file_name != NULL) { rc = ut_file_delete(state); ut_assert_int_equal(rc, 0); } if(ut_link_obj->link_name != NULL) { ut_link_obj->ut_cfs_obj.file_name = ut_link_obj->link_name; rc = ut_file_delete(state); ut_assert_int_equal(rc, 0); } return rc; } /** * Test for hardlink creation * Description: Create a hardlink for file * Strategy: * 1. Create hardlink for file * 2. Lookup for hardlink * 3. Verify output * 4. Get attributes and verify st_nlink count * Expcted behavior: * 1. No errors from CORTXFS API. * 2. Lookup for hardlink should be successful */ static void create_hardlink(void **state) { int rc = 0; char *link_name = "test_hardlink"; cfs_ino_t file_inode = 0LL; struct cfs_fh *fh = NULL; struct ut_link_env *ut_link_obj = LINK_ENV_FROM_STATE(state); struct ut_cfs_params *ut_cfs_obj = &ut_link_obj->ut_cfs_obj; ut_link_obj->link_name = link_name; struct stat *stat_out; time_t cur_time; time(&cur_time); rc = cfs_link(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->file_inode, &ut_cfs_obj->current_inode, link_name); ut_assert_int_equal(rc, 0); rc = cfs_lookup(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->current_inode, link_name, &file_inode); ut_assert_int_equal(rc, 0); ut_assert_int_equal(ut_cfs_obj->file_inode, file_inode); rc = cfs_fh_from_ino(ut_cfs_obj->cfs_fs, &ut_cfs_obj->file_inode, &fh); ut_assert_int_equal(rc, 0); stat_out = cfs_fh_stat(fh); ut_assert_int_equal(stat_out->st_nlink, 2); if(difftime(stat_out->st_ctime, cur_time) < 0) { ut_assert_true(0); } if (fh != NULL) { cfs_fh_destroy(fh); } } /** * Test for longname hardlink creation * Description: Create a hardlink with longname for file * Strategy: * 1. Create longname hardlink for file * 2. Lookup for hardlink * 3. Verify output * 4. Get attributes and verify st_nlink count and changed c_time * Expcted behavior: * 1. No errors from CORTXFS API. * 2. Lookup for hardlink should be successful */ static void create_longname255_hardlink(void **state) { int rc = 0; cfs_ino_t file_inode = 0LL; struct cfs_fh *fh = NULL; char *long_name = "123456789012345678901234567890123456789012345678901" "123456789012345678901234567890123456789012345678901" "123456789012345678901234567890123456789012345678901" "123456789012345678901234567890123456789012345678901" "123456789012345678901234567890123456789012345678901"; struct ut_link_env *ut_link_obj = LINK_ENV_FROM_STATE(state); struct ut_cfs_params *ut_cfs_obj = &ut_link_obj->ut_cfs_obj; ut_link_obj->link_name = long_name; struct stat *stat_out; time_t cur_time; time(&cur_time); ut_assert_int_equal(255, strlen(long_name)); rc = cfs_link(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->file_inode, &ut_cfs_obj->current_inode, long_name); ut_assert_int_equal(rc, 0); rc = cfs_lookup(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->current_inode, long_name, &file_inode); ut_assert_int_equal(rc, 0); ut_assert_int_equal(ut_cfs_obj->file_inode, file_inode); rc = cfs_fh_from_ino(ut_cfs_obj->cfs_fs, &ut_cfs_obj->file_inode, &fh); ut_assert_int_equal(rc, 0); stat_out = cfs_fh_stat(fh); ut_assert_int_equal(stat_out->st_nlink, 2); if(difftime(stat_out->st_ctime, cur_time) < 0) { ut_assert_true(0); } if (fh != NULL) { cfs_fh_destroy(fh); } } /** * Test for hardlink creation and deletion of original file * Description: Create a hardlink for file and delete file * Strategy: * 1. Create hardlink for file * 2. Lookup for hardlink * 3. Delete created file * 4. Lookup for hardlink * 5. Verify output * 6. Get attributes and verify st_nlink count and changed c_time * Expcted behavior: * 1. No errors from CORTXFS API. * 2. Lookup for hardlink should be successful */ static void create_hardlink_delete_original(void **state) { int rc = 0; char *link_name = "test_hardlink"; struct ut_link_env *ut_link_obj = LINK_ENV_FROM_STATE(state); struct ut_cfs_params *ut_cfs_obj = &ut_link_obj->ut_cfs_obj; ut_link_obj->link_name = link_name; cfs_ino_t link_inode = 0LL; struct cfs_fh *fh = NULL; time_t cur_time; rc = cfs_link(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->file_inode, &ut_cfs_obj->current_inode, link_name); ut_assert_int_equal(rc, 0); rc = cfs_lookup(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->current_inode, link_name, &link_inode); ut_assert_int_equal(rc, 0); ut_assert_int_equal(ut_cfs_obj->file_inode, link_inode); rc = cfs_unlink(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->current_inode, NULL, ut_cfs_obj->file_name); ut_assert_int_equal(rc, 0); ut_cfs_obj->file_name = NULL; time(&cur_time); struct stat *stat_out; rc = cfs_fh_from_ino(ut_cfs_obj->cfs_fs, &ut_cfs_obj->file_inode, &fh); ut_assert_int_equal(rc, 0); stat_out = cfs_fh_stat(fh); ut_assert_int_equal(stat_out->st_nlink, 1); if(difftime(stat_out->st_ctime, cur_time) < 0) { ut_assert_true(0); } if (fh != NULL) { cfs_fh_destroy(fh); } } /** * Test for hardlink creation and deletion of link * Description: Create a hardlink for file and delete link * Strategy: * 1. Create hardlink for file * 2. Lookup for hardlink * 3. Delete created file * 4. getattr for file * 5. Verify output * Expcted behavior: * 1. No errors from CORTXFS API. * 2. getattr for file should be successful */ static void create_hardlink_delete_link(void **state) { int rc = 0; char *link_name = "test_hardlink"; struct ut_link_env *ut_link_obj = LINK_ENV_FROM_STATE(state); struct ut_cfs_params *ut_cfs_obj = &ut_link_obj->ut_cfs_obj; ut_link_obj->link_name = link_name; time_t cur_time; cfs_ino_t file_inode = 0LL; struct cfs_fh *fh = NULL; rc = cfs_link(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->file_inode, &ut_cfs_obj->current_inode, link_name); ut_assert_int_equal(rc, 0); rc = cfs_lookup(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->current_inode, link_name, &file_inode); ut_assert_int_equal(rc, 0); ut_assert_int_equal(ut_cfs_obj->file_inode, file_inode); time(&cur_time); rc = cfs_unlink(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->current_inode, NULL, link_name); ut_assert_int_equal(rc, 0); ut_link_obj->link_name = NULL; struct stat *stat_out; rc = cfs_fh_from_ino(ut_cfs_obj->cfs_fs, &ut_cfs_obj->file_inode, &fh); ut_assert_int_equal(rc, 0); stat_out = cfs_fh_stat(fh); if(difftime(stat_out->st_ctime, cur_time) < 0) { ut_assert_true(0); } if (fh != NULL) { cfs_fh_destroy(fh); } } /** * Setup for link_ops test group */ static int link_ops_setup(void **state) { int rc = 0; struct ut_link_env *ut_link_obj = NULL; ut_link_obj = calloc(sizeof(struct ut_link_env), 1); ut_assert_not_null(ut_link_obj); *state = ut_link_obj; rc = ut_cfs_fs_setup(state); ut_assert_int_equal(rc, 0); return rc; } /** * Teardown for link_ops test group */ static int link_ops_teardown(void **state) { int rc = 0; rc = ut_cfs_fs_teardown(state); ut_assert_int_equal(rc, 0); free(*state); return rc; } int main(void) { int rc = 0; char *test_log = "/var/log/cortx/test/ut/ut_cortxfs.log"; printf("Link Tests\n"); rc = ut_load_config(CONF_FILE); if (rc != 0) { printf("ut_load_config: err = %d\n", rc); goto end; } test_log = ut_get_config("cortxfs", "log_path", test_log); rc = ut_init(test_log); if (rc != 0) { printf("ut_init failed, log path=%s, rc=%d.\n", test_log, rc); goto out; } struct test_case test_list[] = { ut_test_case(create_symlink, NULL, symlink_teardown), ut_test_case(create_longname255_symlink, NULL, symlink_teardown), ut_test_case(create_hardlink, hardlink_setup, hardlink_teardown), ut_test_case(create_longname255_hardlink, hardlink_setup, hardlink_teardown), ut_test_case(create_hardlink_delete_original, hardlink_setup, hardlink_teardown), ut_test_case(create_hardlink_delete_link, hardlink_setup, hardlink_teardown), }; int test_count = sizeof(test_list)/sizeof(test_list[0]); int test_failed = 0; test_failed = ut_run(test_list, test_count, link_ops_setup, link_ops_teardown); ut_fini(); ut_summary(test_count, test_failed); out: free(test_log); end: return rc; }
13,370
C
.c
413
29.864407
75
0.708103
Seagate/cortx-fs
3
13
7
AGPL-3.0
9/7/2024, 2:18:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,882,673
ut_cortxfs_helper.c
Seagate_cortx-fs/src/test/ut/ut_cortxfs_helper.c
/* * Filename: ut_cortxfs_helper.c * Description: Functions for fs_open and fs_close required for test * * Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * For any questions about this software or licensing, * please email [email protected] or [email protected]. */ #include "ut_cortxfs_helper.h" #include "ut_cortxfs_endpoint_dummy.h" int ut_cfs_fs_setup(void **state) { int rc = 0; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); char *ut_conf_file = "/tmp/cortxfs/build-cortxfs/test/ut/ut_cortxfs.conf", *def_fs = "testfs"; ut_cfs_obj->cfs_fs = CFS_NULL_FS_CTX; ut_cfs_obj->cred.uid = getuid(); ut_cfs_obj->cred.gid = getgid(); ut_cfs_obj->current_inode = CFS_ROOT_INODE; ut_cfs_obj->parent_inode = CFS_ROOT_INODE; ut_cfs_obj->fs_name = NULL; rc = cfs_init(CFS_DEFAULT_CONFIG, get_endpoint_dummy_ops()); if (rc != 0) { fprintf(stderr, "cfs_init: err = %d\n", rc); goto out; } rc = ut_load_config(ut_conf_file); if (rc != 0) { fprintf(stderr, "ut_load_config: err = %d\n", rc); goto out; } ut_cfs_obj->fs_name = ut_get_config("cortxfs", "fs", def_fs); str256_t fs_name; str256_from_cstr(fs_name, ut_cfs_obj->fs_name, strlen(ut_cfs_obj->fs_name)); rc = 0; rc = cfs_fs_create(&fs_name, NULL); if (rc != 0) { fprintf(stderr, "Failed to create FS %s, rc=%d\n", ut_cfs_obj->fs_name, rc); goto out; } struct cfs_fs *cfs_fs = NULL; rc = cfs_fs_open(ut_cfs_obj->fs_name, &cfs_fs); if (rc != 0) { fprintf(stderr, "Unable to open FS for fs_name:%s, rc=%d !\n", ut_cfs_obj->fs_name, rc); goto out; } ut_cfs_obj->cfs_fs = cfs_fs; out: return rc; } int ut_cfs_fs_teardown(void **state) { int rc = 0; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); cfs_fs_close(ut_cfs_obj->cfs_fs); str256_t fs_name; str256_from_cstr(fs_name, ut_cfs_obj->fs_name, strlen(ut_cfs_obj->fs_name)); rc = cfs_fs_delete(&fs_name); ut_assert_int_equal(rc, 0); free(ut_cfs_obj->fs_name); rc = cfs_fini(); ut_assert_int_equal(rc, 0); return rc; } int ut_file_create(void **state) { int rc = 0; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); cfs_ino_t *pinode = &ut_cfs_obj->parent_inode; struct cfs_fh *parent_fh = NULL; rc = cfs_fh_from_ino(ut_cfs_obj->cfs_fs, pinode, &parent_fh); ut_assert_int_equal(rc, 0); rc = cfs_creat(parent_fh, &ut_cfs_obj->cred, ut_cfs_obj->file_name, 0755, &ut_cfs_obj->file_inode); if (rc) { printf("Failed to create file %s\n", ut_cfs_obj->file_name); } cfs_fh_destroy_and_dump_stat(parent_fh); return rc; } int ut_file_delete(void **state) { int rc = 0; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); rc = cfs_unlink(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->parent_inode, NULL, ut_cfs_obj->file_name); if (rc) { printf("Failed to delete file %s\n", ut_cfs_obj->file_name); } return rc; } int ut_dir_create(void **state) { int rc = 0; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); rc = cfs_mkdir(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->parent_inode, ut_cfs_obj->file_name, 0755, &ut_cfs_obj->file_inode); if (rc) { printf("Failed to create directory %s\n", ut_cfs_obj->file_name); } return rc; } int ut_dir_delete(void **state) { int rc = 0; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); rc = cfs_rmdir(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->parent_inode, ut_cfs_obj->file_name); if (rc) { printf("Failed to delete directory %s\n", ut_cfs_obj->file_name); } return rc; }
4,227
C
.c
129
30.379845
75
0.685117
Seagate/cortx-fs
3
13
7
AGPL-3.0
9/7/2024, 2:18:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,882,674
ut_cortxfs_io_bug_ops.c
Seagate_cortx-fs/src/test/ut/ut_cortxfs_io_bug_ops.c
/* * Filename: ut_cortxfs_io_bug_ops.c * Description: Implementation tests for read and write bugs * * Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * For any questions about this software or licensing, * please email [email protected] or [email protected]. */ #include "ut_cortxfs_helper.h" #define BLOCK_SIZE 4096 #define IO_ENV_FROM_STATE(__state) (*((struct ut_io_env **)__state)) struct ut_io_env { struct ut_cfs_params ut_cfs_obj; char *data; char *buf_in; }; /** * Fill data_str block with given data */ static void ut_fill_data(char *data_str, int size, char data) { int i; for(i = 0; i<size; i++) { data_str[i] = data; } } /** * Setup for io test * Description: Create file. * Strategy: * 1. Create file. * Expected Behavior: * 1. No errors from CORTXFS API. * 2. File creation should be successful. */ static int io_test_setup(void **state) { int rc = 0; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); ut_cfs_obj->file_name = "io_test_file"; rc = ut_file_create(state); ut_assert_int_equal(rc, 0); return rc; } /** * Teardown for io test * Description: Delete file. * Strategy: * 1. Delete file. * Expected Behavior: * 1. No errors from CORTXFS API. * 2. File deletion should be successful. */ static int io_test_teardown(void **state) { int rc = 0; rc = ut_file_delete(state); ut_assert_int_equal(rc, 0); return rc; } /** * Test for read from empty file * Description: Read first block from empty file * Strategy: * 2. Read first block of empty file * Expected Behavior: * 1. No errors from CORTXFS API. * 2. Data read should be zeros. */ static void test_r_empty_file(void **state) { int rc = 0; char *buf_out; cfs_file_open_t fd; struct ut_io_env *ut_io_obj = IO_ENV_FROM_STATE(state); struct ut_cfs_params *ut_cfs_obj = &ut_io_obj->ut_cfs_obj; struct stat stat_in; stat_in.st_size = 0; fd.ino = ut_cfs_obj->file_inode; buf_out = (char *)malloc(sizeof(char) * BLOCK_SIZE); ut_assert_not_null(buf_out); ut_fill_data(buf_out, BLOCK_SIZE, 'a'); rc = cfs_truncate(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->file_inode, &stat_in, STAT_SIZE_SET); ut_assert_int_equal(rc, 0); rc = cfs_read(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &fd, buf_out, BLOCK_SIZE, 0); ut_assert_int_equal(rc, 0); free(buf_out); } /** * Description: Mixed IO ranges for READ and WRITE. * Strategy: * 1. Write (write_offset, write_size) block of data. * 2. Read (read_offset, read_size) block of data. * Expected behavior: * 1. No errors from the DSAL calls. * 2. Read output matches expected output. * * Note: This is helper function, not a test case */ static int rw_mixed_range(void **state, cfs_file_open_t *fd, uint64_t w_offset, uint64_t w_size, uint64_t r_offset, uint64_t r_size) { int rc = 0; char *buf_out; struct ut_io_env *ut_io_obj = IO_ENV_FROM_STATE(state); struct ut_cfs_params *ut_cfs_obj = &ut_io_obj->ut_cfs_obj; buf_out = calloc(sizeof(char), r_size); ut_assert_not_null(buf_out); rc = cfs_write(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, fd, ut_io_obj->buf_in, w_size, w_offset); ut_assert_int_equal(rc, w_size); rc = cfs_read(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, fd, buf_out, r_size, r_offset); if (rc == r_size) { /* Data read from hole should match as expected */ rc = memcmp(ut_io_obj->data, buf_out + w_size, r_size - w_size); ut_assert_int_equal(rc, 0); } else { /* No holes left in a file, we should be reading only written * number of bytes */ ut_assert_int_equal(rc, w_size); } /* Data written should be there in read data bytes */ rc = memcmp(ut_io_obj->buf_in, buf_out, w_size); ut_assert_int_equal(rc, 0); free(buf_out); return rc; } /** * Test to read 4k holes from from medium size file * Description: read 4k holes from from medium size file * Strategy: * 1. Write first block. * 2. Read first and second block (hole). * 3. Verify output. * 4. Repate for each of the blocks in the file. * Expected Behavior: * 1. No errors from the DSAL calls. * 2. Holes read as zeros. * 3. Read output matches expected output. * * Bug Description: * 1. Data read from 2nd 4k block dos not match * with data written. * 2. When block size is 8k, test fails with 1st block * not matching with data written. * 3. Same test when block size and hole size is 2k, 16k * passes without any error. */ static void test_r_4kholes_in_middle(void **state) { int rc = 0, i; const uint64_t blk_sz = 4 << 10; /* 4KB block */ const uint64_t nr_blocks = 16; /* 64KB total */ cfs_file_open_t fd; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); struct stat stat_in; fd.ino = ut_cfs_obj->file_inode; stat_in.st_size = nr_blocks * blk_sz; rc = cfs_truncate(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->file_inode, &stat_in, STAT_SIZE_SET); ut_assert_int_equal(rc, 0); for (i = 0; i < nr_blocks; i++) { rc = rw_mixed_range(state, &fd, (blk_sz * i), blk_sz, (blk_sz * i), (blk_sz * 2)); ut_assert_int_equal(rc, 0); } } /** * Setup for io_ops test group. */ static int io_ops_setup(void **state) { int rc = 0; struct ut_io_env *ut_io_obj = NULL; ut_io_obj = calloc(sizeof(struct ut_io_env), 1); ut_assert_not_null(ut_io_obj); ut_io_obj->data = calloc(sizeof(char), 16 <<10); ut_assert_not_null(ut_io_obj->data); ut_fill_data(ut_io_obj->data, 16 <<10, 0); ut_io_obj->buf_in = calloc(sizeof(char), 16 <<10); ut_fill_data(ut_io_obj->buf_in, 16 <<10, 'a'); *state = ut_io_obj; rc = ut_cfs_fs_setup(state); ut_assert_int_equal(rc, 0); return rc; } /* * Teardown for io_ops test group. */ static int io_ops_teardown(void **state) { int rc = 0; struct ut_io_env *ut_io_obj = IO_ENV_FROM_STATE(state); rc = ut_cfs_fs_teardown(state); ut_assert_int_equal(rc, 0); free(ut_io_obj->data); free(ut_io_obj->buf_in); free(*state); return rc; } int main(void) { int rc = 0; char *test_log = "/var/log/cortx/test/ut/ut_cortxfs.log"; printf("IO Bug tests\n"); rc = ut_load_config(CONF_FILE); if (rc != 0) { printf("ut_load_config: err = %d\n", rc); goto end; } test_log = ut_get_config("cortxfs", "log_path", test_log); rc = ut_init(test_log); if (rc != 0) { printf("ut_init failed, log path=%s, rc=%d.\n", test_log, rc); goto out; } struct test_case test_list[] = { ut_test_case(test_r_empty_file, io_test_setup, io_test_teardown), ut_test_case(test_r_4kholes_in_middle, io_test_setup, io_test_teardown), }; int test_count = sizeof(test_list)/sizeof(test_list[0]); int test_failed = 0; test_failed = ut_run(test_list, test_count, io_ops_setup, io_ops_teardown); ut_fini(); ut_summary(test_count, test_failed); out: free(test_log); end: return rc; }
7,480
C
.c
248
27.870968
79
0.68053
Seagate/cortx-fs
3
13
7
AGPL-3.0
9/7/2024, 2:18:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,882,675
ut_cortxfs_endpoint_dummy.h
Seagate_cortx-fs/src/test/ut/ut_cortxfs_endpoint_dummy.h
/* * Filename: cortxfs_export.h * Description: Declararions of functions used to test cfs_export * * Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * For any questions about this software or licensing, * please email [email protected] or [email protected]. */ #include "cortxfs.h" /* endpoint dummy ops. * * @param - void. * * @return dummy endpoint operations. */ const struct cfs_endpoint_ops* get_endpoint_dummy_ops(void);
1,135
C
.c
26
41.692308
75
0.766938
Seagate/cortx-fs
3
13
7
AGPL-3.0
9/7/2024, 2:18:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,882,676
ut_cortxfs_dir_ops.c
Seagate_cortx-fs/src/test/ut/ut_cortxfs_dir_ops.c
/* * Filename: ut_cortxfs_dir_ops.c * Description: Implementation tests for directory operartions * * Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * For any questions about this software or licensing, * please email [email protected] or [email protected]. */ #include "ut_cortxfs_helper.h" #define DIR_NAME_LEN_MAX 255 #define DIR_ENV_FROM_STATE(__state) (*((struct ut_dir_env **)__state)) struct ut_dir_env { struct ut_cfs_params ut_cfs_obj; char **name_list; int entry_cnt; }; struct readdir_ctx { int index; char *readdir_array[256]; }; /** * Call-back function for readdir */ static bool test_readdir_cb(void *ctx, const char *name, cfs_ino_t child_ino) { struct readdir_ctx *readdir_ctx = ctx; readdir_ctx->readdir_array[readdir_ctx->index++] = strdup(name); return true; } /** * Free readdir array */ static void readdir_ctx_fini(struct readdir_ctx *ctx) { int i; for (i = 0; i < ctx->index; i++) { free(ctx->readdir_array[i]); } } /** * Verify readdir content */ static void verify_dentries(struct readdir_ctx *ctx, struct ut_dir_env *env, int entry_start) { int i; ut_assert_int_equal(env->entry_cnt, ctx->index); for (i = 0; i < ctx->index; i++) { ut_assert_string_equal(env->name_list[entry_start + i], ctx->readdir_array[i]); } } /** * Setup for reading root directory content * Description: Create directory in root directory. * Strategy: * 1. Create a directory in root directory * Expected behavior: * 1. No errors from CORTXFS API. * 2. Directory creation should be successful. */ static int readdir_root_dir_setup(void **state) { int rc = 0; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); ut_dir_obj->name_list[0] = "test_readdir_root_dir"; ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[0]; ut_dir_obj->entry_cnt = 1; rc = ut_dir_create(state); ut_assert_int_equal(rc, 0); return rc; } /** * Test for reading root directory content * Description: Read root directory. * Strategy: * 1. Read root directory * 2. Verify readdir content. * Expected behavior: * 1. No errors from CORTXFS API. * 2. The readdir content comparision should not fail. */ static void readdir_root_dir(void **state) { int rc = 0; cfs_ino_t root_inode = CFS_ROOT_INODE; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); struct ut_cfs_params *ut_cfs_obj = &ut_dir_obj->ut_cfs_obj; struct readdir_ctx readdir_ctx[1] = {{ .index = 0, }}; rc = cfs_readdir(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &root_inode, test_readdir_cb, readdir_ctx); ut_assert_int_equal(rc, 0); verify_dentries(readdir_ctx, ut_dir_obj, 0); readdir_ctx_fini(readdir_ctx); } /** * Teardown for directory realated tests * Description: Delete a directory. * Strategy: * 1. Delete directory. * Expected behavior: * 1. No errors from CORTXFS API. * 2. Directory deletion should be successful. */ static int dir_test_teardown(void **state) { int rc = 0; rc = ut_dir_delete(state); ut_assert_int_equal(rc, 0); return rc; } /** * Setup for reading sub directory content * Description: Create directories. * Strategy: * 1. Create a directory d1 in root directory * 2. Create directory d2 inside d1 * Expected behavior: * 1. No errors from CORTXFS API. * 2. Directory creation should be successful. */ static int readdir_sub_dir_setup(void **state) { int rc = 0; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); ut_dir_obj->name_list[0] = "test_read_sub_dir"; ut_dir_obj->name_list[1] = "test_read_subdir"; ut_dir_obj->entry_cnt = 1; ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[0]; rc = ut_dir_create(state); ut_assert_int_equal(rc, 0); ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[1]; ut_dir_obj->ut_cfs_obj.parent_inode = ut_dir_obj->ut_cfs_obj.file_inode; rc = ut_dir_create(state); ut_assert_int_equal(rc, 0); return rc; } /** * Test for reading sub directory content * Description: Read sub directory. * Strategy: * 3. Read directory d1 * 4. Verify readdir content. * Expected behavior: * 1. No errors from CORTXFS API. * 2. The readdir content comparision should not fail. */ static void readdir_sub_dir(void **state) { int rc = 0; cfs_ino_t dir_inode = 0LL; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); struct ut_cfs_params *ut_cfs_obj = &ut_dir_obj->ut_cfs_obj; struct readdir_ctx readdir_ctx[1] = {{ .index = 0, }}; rc = cfs_lookup(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->current_inode, ut_dir_obj->name_list[0], &dir_inode); ut_assert_int_equal(rc, 0); rc = cfs_readdir(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &dir_inode, test_readdir_cb, readdir_ctx); ut_assert_int_equal(rc, 0); verify_dentries(readdir_ctx, ut_dir_obj, 1); readdir_ctx_fini(readdir_ctx); } /** * Teardown for reading sub directory content test * Description: Delete directories. * Strategy: * 1. Delete a directory d1 in root directory * 2. Delete directory d2 inside d1 * Expected behavior: * 1. No errors from CORTXFS API. * 2. Directory deletion should be successful. */ static int readdir_sub_dir_teardown(void **state) { int rc = 0; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[1]; rc = ut_dir_delete(state); assert_int_equal(rc, 0); ut_dir_obj->ut_cfs_obj.parent_inode = CFS_ROOT_INODE; ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[0]; rc = ut_dir_delete(state); assert_int_equal(rc, 0); return rc; } /** * Setup for reading directory content test * Description: Create file and directory * Strategy: * 1. Create a directory d1 in root directory * 3. Create file f1 in root directory * Expected behavior: * 1. No errors from CORTXFS API. * 2. File and directory creation should be successful */ static int readdir_file_and_dir_setup(void **state) { int rc = 0; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); ut_dir_obj->name_list[0] = "test_read_dir"; ut_dir_obj->name_list[1] = "test_read_file"; ut_dir_obj->entry_cnt = 2; ut_dir_obj->ut_cfs_obj.parent_inode = CFS_ROOT_INODE; ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[0]; rc = ut_file_create(state); ut_assert_int_equal(rc, 0); ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[1]; rc = ut_dir_create(state); ut_assert_int_equal(rc, 0); return rc; } /** * Test for reading directory content * Description: Read directory. * Strategy: * 1. Read root directory * 2. Verify readdir content. * Expected behavior: * 1. No errors from CORTXFS API. * 2. The readdir content comparision should not fail. */ static void readdir_file_and_dir(void **state) { int rc = 0; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); struct ut_cfs_params *ut_cfs_obj = &ut_dir_obj->ut_cfs_obj; struct readdir_ctx readdir_ctx[1] = {{ .index = 0, }}; rc = cfs_readdir(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->parent_inode, test_readdir_cb, readdir_ctx); ut_assert_int_equal(rc, 0); verify_dentries(readdir_ctx, ut_dir_obj, 0); readdir_ctx_fini(readdir_ctx); } /** * Teardown for reading directory content test * Description: Delete file and directory * Strategy: * 1. Delete a directory d1 in root directory * 2. Delete file f1 in root directory * Expected behavior: * 1. No errors from CORTXFS API. * 2. File and directory creation should be successful */ static int readdir_file_and_dir_teardown(void **state) { int rc = 0; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[0]; rc = ut_file_delete(state); ut_assert_int_equal(rc, 0); ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[1]; rc = ut_dir_delete(state); ut_assert_int_equal(rc, 0); return rc; } /** * Setup for reading empty directory content * Description: Create directory. * Strategy: * 1. Create a directory d1 in root directory * Expected behavior: * 1. No errors from CORTXFS API. * 2. Directory creation should be succssful */ static int readdir_empty_dir_setup(void **state) { int rc = 0; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); ut_dir_obj->name_list[0] = "test_read_empty_dir"; ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[0]; ut_dir_obj->entry_cnt = 0; rc = ut_dir_create(state); ut_assert_int_equal(rc, 0); return rc; } /** * Test for reading empty directory content * Description: Read empty directory. * Strategy: * 1. Read d1 directory * 2. Verify readdir content to be nothing. * Expected behavior: * 1. No errors from CORTXFS API. * 2. The readdir content should be empty. */ static void readdir_empty_dir(void **state) { int rc = 0; cfs_ino_t dir_inode = 0LL; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); struct ut_cfs_params *ut_cfs_obj = &ut_dir_obj->ut_cfs_obj; struct readdir_ctx readdir_ctx[1] = {{ .index = 0, }}; rc = cfs_lookup(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->parent_inode, ut_dir_obj->name_list[0], &dir_inode); ut_assert_int_equal(rc, 0); rc = cfs_readdir(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &dir_inode, test_readdir_cb, readdir_ctx); ut_assert_int_equal(rc, 0); verify_dentries(readdir_ctx, ut_dir_obj, 0); readdir_ctx_fini(readdir_ctx); } /** * Setup for reading directory which contains multpile directories * Description: Create directories. * Strategy: * 1. Create a directory d0 in root directory * 2. Create directories d1 to d8 in d0 * Expected behavior: * 1. No errors from CORTXFS API. * 2. Directory creation should be succssful. */ static int readdir_multiple_dir_setup(void **state) { int rc = 0; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); ut_dir_obj->name_list[0] = "test_read_dir"; ut_dir_obj->name_list[1] = "dir1"; ut_dir_obj->name_list[2] = "dir2"; ut_dir_obj->name_list[3] = "dir3"; ut_dir_obj->name_list[4] = "dir4"; ut_dir_obj->name_list[5] = "dir5"; ut_dir_obj->name_list[6] = "dir6"; ut_dir_obj->name_list[7] = "dir7"; ut_dir_obj->name_list[8] = "dir8"; ut_dir_obj->entry_cnt = 8; ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[0]; rc = ut_dir_create(state); ut_assert_int_equal(rc, 0); ut_dir_obj->ut_cfs_obj.parent_inode = ut_dir_obj->ut_cfs_obj.file_inode; int i; for (i = 0; i<8; i ++) { ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[i+1]; rc = ut_dir_create(state); ut_assert_int_equal(rc, 0); } return rc; } /** * Test for reading directory which contains multpile directories * Description: Read nonempty directory. * Strategy: * 1. Read directory d0. * Expected behavior: * 1. No errors from CORTXFS API. * 2. Readdir content should match */ static void readdir_multiple_dir(void **state) { int rc = 0; cfs_ino_t dir_inode = 0LL; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); struct ut_cfs_params *ut_cfs_obj = &ut_dir_obj->ut_cfs_obj; struct readdir_ctx readdir_ctx[1] = {{ .index = 0, }}; rc = cfs_lookup(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->current_inode, ut_dir_obj->name_list[0], &dir_inode); ut_assert_int_equal(rc, 0); rc = cfs_readdir(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &dir_inode, test_readdir_cb, readdir_ctx); ut_assert_int_equal(rc, 0); verify_dentries(readdir_ctx, ut_dir_obj, 1); readdir_ctx_fini(readdir_ctx); } /** * Teardown for reading directory which contains multpile directories * Description: Create directories. * Strategy: * 1. Delete directories d1 to d8 in d0 * 2. Delete a directory d0 in root directory * Expected behavior: * 1. No errors from CORTXFS API. * 2. Directory deletion should be succssful. */ static int readdir_multiple_dir_teardown(void **state) { int rc = 0, i; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); for (i = 1; i<9; i ++) { ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[i]; rc = ut_dir_delete(state); assert_int_equal(rc, 0); } ut_dir_obj->ut_cfs_obj.parent_inode = CFS_ROOT_INODE; ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[0]; rc = ut_dir_delete(state); assert_int_equal(rc, 0); return rc; } /** * Setup for directory creation test. * Description: check if directory exists. * Strategy: * 1. Check if directory exists * Expected behavior: * 1. No errors from CORTXFS API. * 2. The lookup should fail with error -ENOENT */ static int create_dir_setup(void **state) { int rc = 0; cfs_ino_t dir_inode = 0LL; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); ut_cfs_obj->parent_inode = CFS_ROOT_INODE; ut_cfs_obj->file_name = "test_dir"; rc = cfs_lookup(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->parent_inode, ut_cfs_obj->file_name, &dir_inode); ut_assert_int_equal(rc, -ENOENT); rc = 0; return rc; } /** * Test for directory creation. * Description: create a directory. * Strategy: * 1. Create a directory. * 2. Lookup for created directory. * 3. Verify output. * Expected behavior: * 1. No errors from CORTXFS API. * 2. The lookup should verify directory creation. */ static void create_dir(void **state) { int rc = 0; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); cfs_ino_t dir_inode = 0LL; rc = cfs_mkdir(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->current_inode, ut_cfs_obj->file_name, 0755, &dir_inode); ut_assert_int_equal(rc, 0); dir_inode = 0LL; rc = cfs_lookup(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->parent_inode, ut_cfs_obj->file_name, &dir_inode); ut_assert_int_equal(rc, 0); } /** * Setup for existing directory creation. * Description: create a existing directory. * Strategy: * 1. Check if directory exists * 2. Create a directory. * Expected behavior: * 1. No errors from CORTXFS API. * 2. Directory creation should be successful. */ static int create_exist_dir_setup(void **state) { int rc = 0; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); ut_cfs_obj->file_name = "test_exist_dir"; cfs_ino_t dir_inode = 0LL; rc = cfs_lookup(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->parent_inode, ut_cfs_obj->file_name, &dir_inode); ut_assert_int_equal(rc, -ENOENT); rc = cfs_mkdir(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->current_inode, ut_cfs_obj->file_name, 0755, &dir_inode); ut_assert_int_equal(rc, 0); return rc; } /** * Test for existing directory creation. * Description: create a existing directory. * Strategy: * 3. Create existing directory. * Expected behavior: * 1. No errors from CORTXFS API. * 2. Directory creation should fail with error directory exists. */ static void create_exist_dir(void **state) { int rc = 0; cfs_ino_t dir_inode = 0LL; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); rc = cfs_mkdir(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->current_inode, ut_cfs_obj->file_name, 0755, &dir_inode); ut_assert_int_equal(rc, -EEXIST); } /** * Setup for longnamedirectory creation test. * Description: check if directory exists. * Strategy: * 1. Check if directory exists * Expected behavior: * 1. No errors from CORTXFS API. * 2. The lookup should fail with error -ENOENT */ static int create_longname255_dir_setup(void **state) { int rc = 0; cfs_ino_t dir_inode = 0LL; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); ut_cfs_obj->file_name = "123456789012345678901234567890123456789012345" "67890123456789012345678901234567890123456789012345678" "90123456789012345678901234567890123456789012345678901" "23456789012345678901234567890123456789012345678901234" "567890123456789012345678901234567890123456789012345"; ut_assert_int_equal(255, strlen(ut_cfs_obj->file_name)); rc = cfs_lookup(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->parent_inode, ut_cfs_obj->file_name, &dir_inode); ut_assert_int_equal(rc, -ENOENT); rc = 0; return rc; } /** * Test for longname directory creation. * Description: create a longname directory. * Strategy: * 1. Create a longname directory. * 2. Lookup for created directory. * 3. Verify output. * Expected behavior: * 1. No errors from CORTXFS API. * 2. Lookup should verify directory creation */ static void create_longname255_dir(void **state) { int rc = 0; cfs_ino_t dir_inode = 0LL; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); rc = cfs_mkdir(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->current_inode, ut_cfs_obj->file_name, 0755, &dir_inode); ut_assert_int_equal(rc, 0); rc = cfs_lookup(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->parent_inode, ut_cfs_obj->file_name, &dir_inode); ut_assert_int_equal(rc, 0); } /** * Setup for longnamedirectory creation test. * Description: check if directory exists. * Strategy: * 1. Check if directory exists * Expected behavior: * 1. No errors from CORTXFS API. * 2. The lookup should fail with error -ENOENT */ static int create_name_exceed_limit_dir_setup(void **state) { int rc = 0; cfs_ino_t dir_inode = 0LL; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); ut_cfs_obj->file_name = "123456789012345678901234567890123456789012345" "67890123456789012345678901234567890123456789012345678" "90123456789012345678901234567890123456789012345678901" "23456789012345678901234567890123456789012345678901234" "5678901234567890123456789012345678901234567890123456"; if(strlen(ut_cfs_obj->file_name) <= DIR_NAME_LEN_MAX) { ut_assert_true(0); } rc = cfs_lookup(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->parent_inode, ut_cfs_obj->file_name, &dir_inode); ut_assert_int_equal(rc, -ENOENT); rc = 0; return rc; } /** * Test for longname directory creation. * Description: create a longname directory. * Strategy: * 1. Create a longname directory. * 2. Lookup for created directory. * 3. Verify output. * Expected behavior: * 1. No errors from CORTXFS API. * 2. Lookup should verify directory creation */ static void create_name_exceed_limit_dir(void **state) { int rc = 0; cfs_ino_t dir_inode = 0LL; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); rc = cfs_mkdir(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->current_inode, ut_cfs_obj->file_name, 0755, &dir_inode); ut_assert_int_equal(rc, -E2BIG); } /** * Test for current directory creation. * Description: Test mkdir fails with EXIST when the dentry name is ".". * Strategy: * 1. Create a directory with dentry name ".". * Expected behavior: * 1. No errors from CORTXFS API. * 2. Directory creation should fail with error directory exists */ static void create_current_dir(void **state) { int rc = 0; char *dir_name = "."; cfs_ino_t dir_inode = 0LL; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); rc = cfs_mkdir(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->current_inode, dir_name, 0755, &dir_inode); ut_assert_int_equal(rc, -EEXIST); } /** * Test for parent directory creation. * Description: Test if mkdir fails with EXIST when the dentry name is "..". * Strategy: * 1. Create directory with dentry name "..". * Expected behavior: * 1. No errors from CORTXFS API * 2. Directory creation should fail with error directory exists */ static void create_parent_dir(void **state) { int rc = 0; char *dir_name = ".."; cfs_ino_t dir_inode = 0LL; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); rc = cfs_mkdir(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->current_inode, dir_name, 0755, &dir_inode); ut_assert_int_equal(rc, -EEXIST); } /** * Test for root directory creation. * Description: create root directory. * Strategy: * 1. Create a root directory. * Expected behavior: * 1. No errors from CORTXFS API * 2. Directory creation should fail with error directory exists */ static void create_root_dir(void **state) { int rc = 0; char *dir_name = "/"; cfs_ino_t dir_inode = 0LL; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); rc = cfs_mkdir(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, &ut_cfs_obj->current_inode, dir_name, 0755, &dir_inode); ut_assert_int_equal(rc, -EEXIST); } /** * Setup for create_remove_subdir setup */ static int create_remove_subdir_setup(void **state) { int rc = 0; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); ut_dir_obj->name_list[0] = "create_remove_subdir_setup"; ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[0]; ut_dir_obj->entry_cnt = 1; rc = ut_dir_create(state); ut_assert_int_equal(rc, 0); return rc; } /** * Test if ctime and mtime changes for parent dir * after creation and removal of child dir. * Strategy: * 1. Getattr of parent dir * 2. create a subdir * 3. getattr of parent dir * 4. check if ctime and mtime changed * for parent dir or not. * 5. delete child dir. * 6. getattr of parent dir. * 7. check if ctime and mtime changed * for parent dir or not. * Expected behavior: * 1. No errors from CORTXFS API * 2. parent dir ctime and mtime should change * after creation and removal of sub dir. */ static void create_remove_subdir(void **state) { int rc = 0; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); cfs_ino_t *pinode = &ut_cfs_obj->file_inode; cfs_ino_t cinode; struct cfs_fh *pfh_before_create = NULL; struct cfs_fh *pfh_after_create = NULL; struct cfs_fh *pfh_after_rmdir = NULL; struct stat *before_create = NULL; struct stat *after_create = NULL; struct stat *after_rmdir = NULL; rc = cfs_fh_from_ino(ut_cfs_obj->cfs_fs, pinode, &pfh_before_create); ut_assert_int_equal(rc, 0); before_create = cfs_fh_stat(pfh_before_create); rc = cfs_mkdir(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, pinode, "childdir", 0755, &cinode); ut_assert_int_equal(rc, 0); rc = cfs_fh_from_ino(ut_cfs_obj->cfs_fs, pinode, &pfh_after_create); ut_assert_int_equal(rc, 0); after_create = cfs_fh_stat(pfh_after_create); /* if ctime after create has not changed than assert */ if (after_create->st_ctim.tv_sec == before_create->st_ctim.tv_sec && after_create->st_ctim.tv_nsec == before_create->st_ctim.tv_nsec) { ut_assert_true(0); } /* if mtime after create has not changed than assert */ if (after_create->st_mtim.tv_sec == before_create->st_mtim.tv_sec && after_create->st_mtim.tv_nsec == before_create->st_mtim.tv_nsec) { ut_assert_true(0); } rc = cfs_rmdir(ut_cfs_obj->cfs_fs, &ut_cfs_obj->cred, pinode, "childdir"); ut_assert_int_equal(rc, 0); rc = cfs_fh_from_ino(ut_cfs_obj->cfs_fs, pinode, &pfh_after_rmdir); ut_assert_int_equal(rc, 0); after_rmdir = cfs_fh_stat(pfh_after_rmdir); /* if ctime after rmdir has not changed than assert */ if (after_rmdir->st_ctim.tv_sec == after_create->st_ctim.tv_sec && after_rmdir->st_ctim.tv_nsec == after_create->st_ctim.tv_nsec) { ut_assert_true(0); } /* if mtime after rmdir has not changed than assert */ if (after_rmdir->st_mtim.tv_sec == after_create->st_mtim.tv_sec && after_rmdir->st_mtim.tv_nsec == after_create->st_mtim.tv_nsec) { ut_assert_true(0); } if (pfh_before_create != NULL) { cfs_fh_destroy(pfh_before_create); } if (pfh_after_create != NULL) { cfs_fh_destroy(pfh_after_create); } if (pfh_after_rmdir != NULL) { cfs_fh_destroy(pfh_after_rmdir); } } /** * teardown for create_remove_subdir */ static int create_remove_subdir_teardown(void **state) { int rc = 0; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[0]; rc = ut_dir_delete(state); assert_int_equal(rc, 0); return rc; } /** * setup for link_unlink_file test. */ static int link_unlink_file_setup(void **state) { int rc = 0; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); ut_dir_obj->name_list[0] = "link_unlink_file_setup"; ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[0]; ut_dir_obj->entry_cnt = 1; rc = ut_dir_create(state); ut_assert_int_equal(rc, 0); return rc; } /** * Test if ctime and mtime changes for parent dir * after creation and removal of a file inside dir. * Strategy: * 1. Getattr of parent dir * 2. create a file inside parent dir * 3. getattr of parent dir * 4. check if ctime and mtime changed * for parent dir or not. * 5. delete file. * 6. getattr of parent dir. * 7. check if ctime and mtime changed * for parent dir or not. * Expected behavior: * 1. No errors from CORTXFS API * 2. parent dir ctime and mtime should change * after creation and removal of a file inside it. */ static void link_unlink_file(void **state) { int rc = 0; struct ut_cfs_params *ut_cfs_obj = ENV_FROM_STATE(state); cfs_ino_t *pinode = &ut_cfs_obj->file_inode;; cfs_ino_t cinode; struct cfs_fh *parent_fh = NULL; struct cfs_fh *child_fh = NULL; struct stat *parent_stat = NULL; struct stat before_link; struct stat after_link; struct stat after_unlink; rc = cfs_fh_from_ino(ut_cfs_obj->cfs_fs, pinode, &parent_fh); ut_assert_int_equal(rc, 0); parent_stat = cfs_fh_stat(parent_fh); memset(&before_link, 0, sizeof(before_link)); memcpy(&before_link, parent_stat, sizeof(before_link)); rc = cfs_creat(parent_fh, &ut_cfs_obj->cred, "file1", 0755, &cinode); ut_assert_int_equal(rc, 0); memset(&after_link, 0, sizeof(after_link)); memcpy(&after_link, parent_stat, sizeof(after_link)); /* if ctime after link has not changed than assert */ if (after_link.st_ctim.tv_sec == before_link.st_ctim.tv_sec && after_link.st_ctim.tv_nsec == before_link.st_ctim.tv_nsec) { ut_assert_true(0); } /* if mtime after link has not changed than assert */ if (after_link.st_mtim.tv_sec == before_link.st_mtim.tv_sec && after_link.st_mtim.tv_nsec == before_link.st_mtim.tv_nsec) { ut_assert_true(0); } rc = cfs_fh_from_ino(ut_cfs_obj->cfs_fs, &cinode, &child_fh); ut_assert_int_equal(rc, 0); rc = cfs_unlink2(parent_fh, child_fh, &ut_cfs_obj->cred, "file1"); ut_assert_int_equal(rc, 0); memset(&after_unlink, 0, sizeof(after_unlink)); memcpy(&after_unlink, parent_stat, sizeof(after_unlink)); /* if ctime after unlink has not changed than assert */ if (after_link.st_ctim.tv_sec == after_unlink.st_ctim.tv_sec && after_link.st_ctim.tv_nsec == after_unlink.st_ctim.tv_nsec) { ut_assert_true(0); } /* if mtime after unlink has not changed than assert */ if (after_link.st_mtim.tv_sec == after_unlink.st_mtim.tv_sec && after_link.st_mtim.tv_nsec == after_unlink.st_mtim.tv_nsec) { ut_assert_true(0); } cfs_fh_destroy_and_dump_stat(parent_fh); cfs_fh_destroy(child_fh); } static int link_unlink_file_teardown(void **state) { int rc = 0; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[0]; rc = ut_dir_delete(state); assert_int_equal(rc, 0); return rc; } /** * Setup for dir_ops test group */ static int dir_ops_setup(void **state) { int rc = 0; struct ut_dir_env *ut_dir_obj = calloc(sizeof(struct ut_dir_env), 1); ut_assert_not_null(ut_dir_obj); ut_dir_obj->name_list = calloc(sizeof(char *), 10); if(ut_dir_obj->name_list == NULL) { rc = -ENOMEM; ut_assert_true(0); } *state = ut_dir_obj; rc = ut_cfs_fs_setup(state); ut_assert_int_equal(rc, 0); return rc; } /** * Teardown for dir_ops test group */ static int dir_ops_teardown(void **state) { int rc = 0; rc = ut_cfs_fs_teardown(state); ut_assert_int_equal(rc, 0); free(*state); return rc; } /** * Setup for removal of non empty directory. * Description: create a directory and create another directory inside it.. * Strategy: * 1. Create a directory. * 2. Create another directory inside newly created directory in step 2 * Expected behavior: * 1. No errors from CORTXFS API. * 2. Both directory creation should be successful. */ static int delete_nonempty_dir_setup(void **state) { int rc = 0; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); ut_dir_obj->name_list[0] = "test_delete_nonempty_dir"; ut_dir_obj->name_list[1] = "test_delete_nonempty_dir_nested"; ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[0]; rc = ut_dir_create(state); ut_assert_int_equal(rc, 0); ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[1]; ut_dir_obj->ut_cfs_obj.parent_inode = ut_dir_obj->ut_cfs_obj.file_inode; rc = ut_dir_create(state); ut_assert_int_equal(rc, 0); return rc; } /** * Test for deletion of non empty directory * Description: Delete non empty directory. * Strategy: * 1. Delete a directory d1 which contains another directory d2 * Expected behavior: * 1. No errors from CORTXFS API. * 2. Directory deletion should fail with error -ENOTEMPTY. */ static void delete_nonempty_dir(void **state) { int rc = 0; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); cfs_ino_t parent_inode_tmp = ut_dir_obj->ut_cfs_obj.parent_inode; ut_dir_obj->ut_cfs_obj.parent_inode = CFS_ROOT_INODE; ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[0]; rc = ut_dir_delete(state); /* Reverting to original parent(d1) as it will be used in teardown to delete d2 */ ut_dir_obj->ut_cfs_obj.parent_inode = parent_inode_tmp; assert_int_equal(rc, -ENOTEMPTY); } /** * Teardown for deleting non empty directory test * Description: Delete directories. * Strategy: * 1. Delete directory d2 inside d1 * 2. Delete a directory d1 in root directory * Expected behavior: * 1. No errors from CORTXFS API. * 2. Directory deletion should be successful. */ static int delete_nonempty_dir_teardown(void **state) { int rc = 0; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); /* Delete directory d2 inside d1 */ ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[1]; rc = ut_dir_delete(state); assert_int_equal(rc, 0); /* Delete a directory d1 in root directory */ ut_dir_obj->ut_cfs_obj.parent_inode = CFS_ROOT_INODE; ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[0]; rc = ut_dir_delete(state); assert_int_equal(rc, 0); return rc; } /** * Test for deletion of non existing directory * Description: Delete non existing directory. * Strategy: * 1. Delete a directory d1 which does not exist * Expected behavior: * 1. No errors from CORTXFS API. * 2. Directory deletion should fail with error -ENOENT. */ static void delete_nonexistent_dir(void **state) { int rc = 0; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); ut_dir_obj->ut_cfs_obj.file_name = "test_nonexistent_dir"; rc = ut_dir_delete(state); assert_int_equal(rc, -ENOENT); } /** * Setup for deletion of empty directory. * Description: create a directory * Strategy: * 1. Create a directory. * Expected behavior: * 1. No errors from CORTXFS API. * 2. Directory creation should be successful. */ static int delete_empty_dir_setup(void **state) { int rc = 0; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); ut_dir_obj->name_list[0] = "test_delete_empty_dir"; ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[0]; rc = ut_dir_create(state); ut_assert_int_equal(rc, 0); return rc; } /** * Test for deletion of empty directory * Description: Delete empty directory. * Strategy: * 1. Delete a directory which is empty * Expected behavior: * 1. No errors from CORTXFS API. * 2. Directory deletion should be successful. */ static void delete_empty_dir(void **state) { int rc = 0; struct ut_dir_env *ut_dir_obj = DIR_ENV_FROM_STATE(state); ut_dir_obj->ut_cfs_obj.file_name = ut_dir_obj->name_list[0]; rc = ut_dir_delete(state); assert_int_equal(rc, 0); } int main(void) { int rc = 0; char *test_log = "/var/log/cortx/test/ut/ut_cortxfs.log"; printf("Directory tests\n"); rc = ut_load_config(CONF_FILE); if (rc != 0) { printf("ut_load_config: err = %d\n", rc); goto end; } test_log = ut_get_config("cortxfs", "log_path", test_log); rc = ut_init(test_log); if (rc != 0) { printf("ut_init failed, log path=%s, rc=%d.\n", test_log, rc); goto out; } struct test_case test_list[] = { ut_test_case(readdir_root_dir, readdir_root_dir_setup, dir_test_teardown), ut_test_case(readdir_file_and_dir, readdir_file_and_dir_setup, readdir_file_and_dir_teardown), ut_test_case(readdir_sub_dir, readdir_sub_dir_setup, readdir_sub_dir_teardown), ut_test_case(readdir_empty_dir,readdir_empty_dir_setup, dir_test_teardown), ut_test_case(readdir_multiple_dir, readdir_multiple_dir_setup, readdir_multiple_dir_teardown), ut_test_case(create_dir, create_dir_setup, dir_test_teardown), ut_test_case(create_exist_dir, create_exist_dir_setup, dir_test_teardown), ut_test_case(create_longname255_dir, create_longname255_dir_setup, dir_test_teardown), ut_test_case(create_name_exceed_limit_dir, create_name_exceed_limit_dir_setup, NULL), ut_test_case(create_current_dir, NULL, NULL), ut_test_case(create_parent_dir, NULL, NULL), ut_test_case(create_root_dir, NULL, NULL), ut_test_case(create_remove_subdir, create_remove_subdir_setup, create_remove_subdir_teardown), ut_test_case(link_unlink_file, link_unlink_file_setup, link_unlink_file_teardown), ut_test_case(delete_nonempty_dir, delete_nonempty_dir_setup, delete_nonempty_dir_teardown), ut_test_case(delete_nonexistent_dir, NULL, NULL), ut_test_case(delete_empty_dir, delete_empty_dir_setup, NULL), }; int test_count = sizeof(test_list)/sizeof(test_list[0]); int test_failed = 0; test_failed = ut_run(test_list, test_count, dir_ops_setup, dir_ops_teardown); ut_fini(); ut_summary(test_count, test_failed); out: free(test_log); end: return rc; }
34,519
C
.c
1,069
29.84565
83
0.701224
Seagate/cortx-fs
3
13
7
AGPL-3.0
9/7/2024, 2:18:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,882,677
ut_cortxfs_fs_ops.c
Seagate_cortx-fs/src/test/ut/ut_cortxfs_fs_ops.c
/* * Filename: ut_cortxfs_fs.c * Description: implementation tests for cfs_fs * * Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * For any questions about this software or licensing, * please email [email protected] or [email protected]. */ #include "ut_cortxfs_helper.h" #include "ut_cortxfs_endpoint_dummy.h" struct collection_item *cfg_items; static void test_cfs_fs_create(void) { int rc = 0; char *name = "cortxfs"; str256_t fs_name; str256_from_cstr(fs_name, name, strlen(name)); rc = cfs_fs_create(&fs_name, NULL); ut_assert_int_equal(rc, 0); } static void test_cfs_fs_delete(void) { int rc = 0; char *name = "cortxfs"; str256_t fs_name; str256_from_cstr(fs_name, name, strlen(name)); rc = cfs_fs_delete(&fs_name); ut_assert_int_equal(rc, 0); } static int test_cfs_cb(const struct cfs_fs_list_entry *list, void *args) { int rc = 0; if (args != NULL) { rc = -EINVAL; goto out; } printf("CB cortxfs name = %s\n", list->fs_name->s_str); out: return rc; } static void test_cfs_fs_scan(void) { int rc = 0; rc = cfs_fs_scan_list(test_cfs_cb, (void *)0); ut_assert_int_equal(rc, 0); } int main(void) { int rc = 0; char *test_log = "/var/log/cortx/test/ut/ut_cortxfs.log"; printf("FS Tests\n"); rc = ut_load_config(CONF_FILE); if (rc != 0) { printf("ut_load_config: err = %d\n", rc); goto end; } test_log = ut_get_config("cortxfs", "log_path", test_log); rc = ut_init(test_log); if (rc != 0) { printf("ut_init failed, log path=%s, rc=%d.\n", test_log, rc); exit(1); } rc = cfs_init(CFS_DEFAULT_CONFIG, get_endpoint_dummy_ops()); if (rc) { printf("Failed to intitialize cortxfs\n"); goto out; } struct test_case test_list[] = { ut_test_case(test_cfs_fs_create, NULL, NULL), ut_test_case(test_cfs_fs_delete, NULL, NULL), ut_test_case(test_cfs_fs_scan, NULL, NULL), }; int test_count = sizeof(test_list)/sizeof(test_list[0]); int test_failed = 0; test_failed = ut_run(test_list, test_count, NULL, NULL); cfs_fini(); ut_fini(); ut_summary(test_count, test_failed); out: free(test_log); end: return rc; }
2,791
C
.c
93
27.860215
75
0.704562
Seagate/cortx-fs
3
13
7
AGPL-3.0
9/7/2024, 2:18:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,882,678
ut_cortxfs_xattr_file_ops.c
Seagate_cortx-fs/src/test/ut/ut_cortxfs_xattr_file_ops.c
/* * Filename: cortxfs_xattr_ops.c * Description: Implementation tests for xattr * * Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * For any questions about this software or licensing, * please email [email protected] or [email protected]. */ #include "cortxfs_xattr_ops.h" #ifndef ENABLE_TSDB_ADDB #define ENABLE_TSDB_ADDB #endif #include <perf/perf-counters.h> #include <pthread.h> pthread_key_t perfc_tls_key; uint8_t perfc_tls_key_check = PERFC_INVALID_ID; /** * Setup for xattr test group. */ static int xattr_ops_setup(void **state) { int rc = 0; struct ut_xattr_env *ut_xattr_obj = NULL; ut_xattr_obj = calloc(sizeof(struct ut_xattr_env), 1); ut_assert_not_null(ut_xattr_obj); ut_xattr_obj->xattr = calloc(sizeof(char *), 8); if( ut_xattr_obj->xattr == NULL) { ut_assert_true(0); rc = -ENOMEM; } *state = ut_xattr_obj; rc = ut_cfs_fs_setup(state); ut_assert_int_equal(rc, 0); ut_xattr_obj->ut_cfs_obj.file_name = "test_xattr_file"; ut_xattr_obj->ut_cfs_obj.file_inode = 0LL; *state = ut_xattr_obj; rc = ut_file_create(state); ut_assert_int_equal(rc, 0); return rc; } /** * Teardown for xattr test group */ static int xattr_ops_teardown(void **state) { int rc = 0; rc = ut_file_delete(state); ut_assert_int_equal(rc, 0); rc = ut_cfs_fs_teardown(state); ut_assert_int_equal(rc, 0); free(*state); return rc; } int main(void) { int rc = 0; char *test_log = "/var/log/cortx/test/ut/xattr_file_ops.log"; /* * uncomment below statement to enable addb traces in this UT * perfc_tsdb_setup(); */ printf("Xattr file Tests\n"); rc = ut_init(test_log); if (rc != 0) { printf("ut_init failed, log path=%s, rc=%d.\n", test_log, rc); exit(1); } struct test_case test_list[] = { ut_test_case(set_exist_xattr, set_exist_xattr_setup, NULL), ut_test_case(set_nonexist_xattr, NULL, NULL), ut_test_case(replace_exist_xattr, replace_exist_xattr_setup, NULL), ut_test_case(replace_nonexist_xattr, NULL, NULL), ut_test_case(get_exist_xattr, get_exist_xattr_setup, NULL), ut_test_case(get_nonexist_xattr, NULL, NULL), ut_test_case(remove_exist_xattr, remove_exist_xattr_setup, NULL), ut_test_case(remove_nonexist_xattr, NULL, NULL), ut_test_case(listxattr_test, listxattr_test_setup, listxattr_test_teardown), }; int test_count = sizeof(test_list)/sizeof(test_list[0]); int test_failed = 0; test_failed = ut_run(test_list, test_count, xattr_ops_setup, xattr_ops_teardown); ut_fini(); ut_summary(test_count, test_failed); return 0; }
3,226
C
.c
97
30.948454
75
0.722437
Seagate/cortx-fs
3
13
7
AGPL-3.0
9/7/2024, 2:18:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,882,680
cfs_perfc.h
Seagate_cortx-fs/src/include/cfs_perfc.h
/* * Filename: cfs_perfc.h * Description: This module defines performance counters and helpers. * * Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * For any questions about this software or licensing, * please email [email protected] or [email protected]. */ #ifndef __CFS_PERF_COUNTERS_H_ #define __CFS_PERF_COUNTERS_H_ /******************************************************************************/ #include "perf/tsdb.h" /* ACTION_ID_BASE */ #include "operation.h" #include <pthread.h> #include <string.h> #include "debug.h" #include "perf/perf-counters.h" enum perfc_cfs_function_tags { PFT_CFS_START = PFTR_RANGE_1_START, PFT_CFS_READ, PFT_CFS_WRITE, PFT_CFS_GETATTR, PFT_CFS_SETATTR, PFT_CFS_ACCESS, PFT_CFS_MKDIR, PFT_CFS_RMDIR, PFT_CFS_READDIR, PFT_CFS_LOOKUP, PFT_CFS_CREATE_EX, PFT_CFS_CREATE, PFT_CFS_END = PFTR_RANGE_1_END }; enum perfc_cfs_entity_attrs { PEA_CFS_START = PEAR_RANGE_1_START, PEA_R_C_COUNT, PEA_R_C_OFFSET, PEA_R_C_RES_RC, PEA_GETATTR_RES_RC, PEA_SETATTR_RES_RC, PEA_ACCESS_FLAGS, PEA_ACCESS_RES_RC, PEA_CFS_CREATE_PARENT_INODE, PEA_CFS_NEW_FILE_INODE, PEA_CFS_RES_RC, PEA_CFS_END = PEAR_RANGE_1_END }; enum perfc_cfs_entity_maps { PEM_CFS_START = PEMR_RANGE_1_START, PEM_CFS_TO_NFS, PEM_CFS_END = PEMR_RANGE_1_END }; /******************************************************************************/ #endif /* __CFS_PERF_COUNTERS_H_ */
2,104
C
.c
63
31.492063
80
0.691626
Seagate/cortx-fs
3
13
7
AGPL-3.0
9/7/2024, 2:18:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,882,684
error_handler.c
Seagate_cortx-fs/src/management/error_handler.c
/* * Filename: error_handler.c * Description: Response error handling APIs * * Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * For any questions about this software or licensing, * please email [email protected] or [email protected]. */ #include "internal/error_handler.h" #include <errno.h> const char *error_resp_messages[] = { "Invalid error response ID", /* fs create api error response */ "The filesystem name specified is not valid.", "The filesystem name you tried to create already exists.", /* fs delete api error response */ "The specified filesystem does not exist.", "The filesystem you tried to delete is being exported.", "The filesystem you tried to delete is not empty.", /* Generic error responses */ "The ETag should not be passed for a resource which is not modifiable.", "The HASH specified did not match what we received.", "The Object ETag is not sent.", "Invalid payload data passed.", "Invalid parameters passed with the API path.", /* Default error response */ "Generic error message. Check cortx logs for more information." }; const char* fs_create_errno_to_respmsg(int err_code) { enum error_resp_id resp_id; switch (err_code) { case EINVAL: resp_id = ERR_RES_INVALID_FSNAME; break; case EEXIST: resp_id = ERR_RES_FS_EXIST; break; /* Since filesystem name cannot be modified. */ case INVALID_ETAG: resp_id = ERR_RES_INVALID_ETAG; break; case INVALID_PAYLOAD: resp_id = ERR_RES_INVALID_PAYLOAD; break; default: resp_id = ERR_RES_DEFAULT; } return error_resp_messages[resp_id]; } const char* fs_delete_errno_to_respmsg(int err_code) { enum error_resp_id resp_id; switch (err_code) { case ENOENT: resp_id = ERR_RES_FS_NONEXIST; break; case EINVAL: resp_id = ERR_RES_FS_EXPORT_EXIST; break; case ENOTEMPTY: resp_id = ERR_RES_FS_NOT_EMPTY; break; case BAD_DIGEST: resp_id = ERR_RES_BAD_DIGEST; break; case MISSING_ETAG: resp_id = ERR_RES_MISSING_ETAG; break; case INVALID_PAYLOAD: resp_id = ERR_RES_INVALID_PAYLOAD; break; case INVALID_PATH_PARAMS: resp_id = ERR_RES_INVALID_PATH_PARAMS; break; default: resp_id = ERR_RES_DEFAULT; } return error_resp_messages[resp_id]; }
2,893
C
.c
90
29.866667
75
0.747402
Seagate/cortx-fs
3
13
7
AGPL-3.0
9/7/2024, 2:18:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,882,687
cortxfs_fh.c
Seagate_cortx-fs/src/cortxfs/cortxfs_fh.c
/* * Filename: cortxfs_fh.c * Description: CORTXFS File Handle API implementation. * * Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * For any questions about this software or licensing, * please email [email protected] or [email protected]. */ #include <kvstore.h> #include "cortxfs.h" #include "cortxfs_internal.h" #include "cortxfs_fh.h" #include <debug.h> #include <string.h> /* strcmp() */ #include <str.h> /* str256_t */ #include <errno.h> /* EINVAL */ #include <common/helpers.h> /* RC_WRAP_LABEL */ #include <common.h> /* unlikely */ #include <common/log.h> /* log_err() */ #include "kvtree.h" /* kvtree_lookup() */ #include "operation.h" /* perf tracepoints */ #include <cfs_perfc.h> /** * A unique key to be used in containers (maps, sets). * TODO: It will be replaced by fid of the file * or a combination of FSFid+FileFid. * NOTE: This is not to be stored in kvs(kvstore). * This is only in memory. * @todo: find a better name than cfs_fh_key, * since *_key names are used by keys stored in kvs. */ struct cfs_fh_key { struct cfs_fs *fs; uint64_t file; }; struct cfs_fh { /* In memory representation of a NSAL kvnode which is linked to a * kvtree. This contains the basic attributes (stats) of a file */ struct kvnode f_node; /* A file system context on which file/directory/symlink is created */ struct cfs_fs *fs; /* TODO: Add FID as an unique key, which will be used in containers * maps, sets */ struct cfs_fh_key key; /* @TODO: Following things can be implemented * 1. Add synchronization primitives to resolve the concurrency * issue * 2. Add ref count to know about file handle in use by multiple * front ends (eg: NFS, CIFS etc) which help to take decision whether * to release FH or not * 3. Cache system attributes associated with a file * 4. Add a file state to make certain decision when multiple users * are using it, like delete on close */ }; /** Initialize an empty invalid FH instance */ #define CFS_FH_INIT (struct cfs_fh) { .f_node = KVNODE_INIT_EMTPY } inline bool cfs_fh_invariant(const struct cfs_fh *fh) { bool rc = false; /* A FH should have * Filesystem pointer set. * File handle kvnode should be initialized properly * File handle should have valid inode */ if (fh->fs != NULL && kvnode_invariant(&fh->f_node)) { struct stat *stat = cfs_fh_stat(fh); cfs_ino_t ino = stat->st_ino; rc = (ino >= CFS_ROOT_INODE); } return rc; } struct cfs_fh_serialized { uint64_t fsid; cfs_ino_t ino_num; }; struct cfs_fs *cfs_fs_from_fh(const struct cfs_fh *fh) { dassert(fh); dassert(cfs_fh_invariant(fh)); return fh->fs; } struct stat *cfs_fh_stat(const struct cfs_fh *fh) { dassert(fh); return cfs_get_stat2(&fh->f_node); } struct kvnode *cfs_kvnode_from_fh(struct cfs_fh *fh) { dassert(fh); dassert(cfs_fh_invariant(fh)); return &fh->f_node; } static inline void cfs_fh_init_key(struct cfs_fh *fh) { struct stat *stat = cfs_fh_stat(fh); fh->key.file = stat->st_ino; fh->key.fs = fh->fs; } node_id_t *cfs_node_id_from_fh(struct cfs_fh *fh) { dassert(fh); dassert(cfs_fh_invariant(fh)); return &fh->f_node.node_id; } cfs_ino_t *cfs_fh_ino(struct cfs_fh *fh) { struct stat *stat = cfs_fh_stat(fh); return (cfs_ino_t *)&stat->st_ino; } int cfs_fh_from_ino(struct cfs_fs *fs, const cfs_ino_t *ino_num, struct cfs_fh **fh) { int rc; struct cfs_fh *newfh = NULL; struct kvstore *kvstor = kvstore_get(); struct kvnode node = KVNODE_INIT_EMTPY; dassert(kvstor && fs && ino_num && fh); RC_WRAP_LABEL(rc, out, cfs_kvnode_load, &node, fs->kvtree, ino_num); /* A caller for this API who uses/caches this FH, will be responsible * for freeing up this FH, caller should be calling cfs_fh_destroy to * release this FH */ RC_WRAP_LABEL(rc, out, kvs_alloc, kvstor, (void **) &newfh, sizeof(struct cfs_fh)); newfh->f_node = node; newfh->fs = fs; cfs_fh_init_key(newfh); dassert(cfs_fh_invariant(newfh)); *fh = newfh; newfh = NULL; out: return rc; } static inline int __cfs_fh_lookup(const cfs_cred_t *cred, struct cfs_fh *parent_fh, const char *name, struct cfs_fh **fh) { int rc; str256_t kname; struct cfs_fh *newfh = NULL; struct stat *parent_stat = NULL; struct kvstore *kvstor = kvstore_get(); struct kvnode node = KVNODE_INIT_EMTPY; cfs_ino_t ino; node_id_t pid, id; dassert(cred && parent_fh && name && fh && kvstor); dassert(cfs_fh_invariant(parent_fh)); parent_stat = cfs_fh_stat(parent_fh); RC_WRAP_LABEL(rc, out, cfs_access_check, (cfs_cred_t *) cred, parent_stat, CFS_ACCESS_READ); if ((parent_stat->st_ino == CFS_ROOT_INODE) && (strcmp(name, "..") == 0)) { ino = CFS_ROOT_INODE; } else { str256_from_cstr(kname, name, strlen(name)); pid = parent_fh->f_node.node_id; RC_WRAP_LABEL(rc, out, kvtree_lookup, parent_fh->fs->kvtree, &pid, &kname, &id); node_id_to_ino(&id, &ino); } dassert(ino >= CFS_ROOT_INODE); RC_WRAP_LABEL(rc, out, cfs_kvnode_load, &node, parent_fh->fs->kvtree, &ino); RC_WRAP_LABEL(rc, out, kvs_alloc, kvstor, (void **) &newfh, sizeof(struct cfs_fh)); newfh->fs = parent_fh->fs; newfh->f_node = node; cfs_fh_init_key(newfh); dassert(cfs_fh_invariant(newfh)); *fh = newfh; newfh = NULL; /* FIXME: Shouldn't we update parent.atime here? */ out: if (newfh) { cfs_fh_destroy(newfh); } return rc; } int cfs_fh_lookup(const cfs_cred_t *cred, struct cfs_fh *parent_fh, const char *name, struct cfs_fh **fh) { int rc; perfc_trace_inii(PFT_CFS_LOOKUP, PEM_CFS_TO_NFS); rc = __cfs_fh_lookup(cred, parent_fh, name, fh); perfc_trace_finii(PERFC_TLS_POP_VERIFY); return rc; } void cfs_fh_destroy(struct cfs_fh *fh) { struct kvstore *kvstor = kvstore_get(); dassert(kvstor && fh); dassert(cfs_fh_invariant(fh)); /* Note: As of now, destroying FH does not update the stats in backend * because those are stale, the reason for that is FH is not supplied * as input param to each of the cortxfs API which can modify the stats * of file directly in FH. * TODO: Temp_FH_op - to be removed * Uncomment the logic to dump the stats associated with FH once FH is * present everywhere all the update happens to FH */ /* cfs_set_stat(&fh->f_node); */ kvnode_fini(&fh->f_node); kvs_free(kvstor, fh); } void cfs_fh_destroy_and_dump_stat(struct cfs_fh *fh) { struct kvstore *kvstor = kvstore_get(); dassert(kvstor && fh); dassert(cfs_fh_invariant(fh)); cfs_set_stat(&fh->f_node); kvnode_fini(&fh->f_node); kvs_free(kvstor, fh); } int cfs_fh_getroot(struct cfs_fs *fs, const cfs_cred_t *cred, struct cfs_fh **pfh) { int rc; struct cfs_fh *fh = NULL; struct stat *stat = NULL; cfs_ino_t root_ino = CFS_ROOT_INODE; dassert(fs && cred && pfh); RC_WRAP_LABEL(rc, out, cfs_fh_from_ino, fs, &root_ino, &fh); stat = cfs_fh_stat(fh); RC_WRAP_LABEL(rc, out, cfs_access_check, (cfs_cred_t *) cred, stat, CFS_ACCESS_READ); *pfh = fh; fh = NULL; out: if (unlikely(fh)) { cfs_fh_destroy(fh); } return rc; } int cfs_fh_serialize(const struct cfs_fh *fh, void* buffer, size_t max_size) { int rc = 0; struct stat *stat = NULL; struct cfs_fh_serialized data = { .ino_num = 0 }; dassert(fh && buffer); dassert(cfs_fh_invariant(fh)); if (max_size < sizeof(struct cfs_fh_serialized)) { rc = -ENOBUFS; goto out; } stat = cfs_fh_stat(fh); data.ino_num = (cfs_ino_t)stat->st_ino; /* fsid is ignored */ memcpy(buffer, &data, sizeof(data)); rc = sizeof(data); out: return rc; } int cfs_fh_deserialize(struct cfs_fs *fs, const cfs_cred_t *cred, const void* buffer, size_t buffer_size, struct cfs_fh** pfh) { int rc = 0; struct cfs_fh_serialized data = { .ino_num = 0 }; dassert(fs && cred && buffer && pfh); /* FIXME: We need to check if this function is a subject * to access checks. */ (void) cred; if (buffer_size != sizeof(struct cfs_fh_serialized)) { rc = -EINVAL; goto out; } memcpy(&data, buffer, sizeof(data)); /* data.fsid is ignored */ RC_WRAP_LABEL(rc, out, cfs_fh_from_ino, fs, &data.ino_num, pfh); out: return rc; } size_t cfs_fh_serialized_size(void) { return sizeof(struct cfs_fh_serialized); } int cfs_fh_ser_with_fsid(const struct cfs_fh *fh, uint64_t fsid, void *buffer, size_t max_size) { int rc = 0; struct stat *stat = NULL; struct cfs_fh_serialized data = { .ino_num = 0 }; dassert(fh && buffer); dassert(cfs_fh_invariant(fh)); if (max_size < sizeof(struct cfs_fh_serialized)) { rc = -ENOBUFS; goto out; } stat = cfs_fh_stat(fh); data.ino_num = stat->st_ino;; data.fsid = fsid; memcpy(buffer, &data, sizeof(data)); rc = sizeof(data); out: return rc; } void cfs_fh_key(const struct cfs_fh *fh, void **pbuffer, size_t *psize) { dassert(fh && pbuffer && psize); *pbuffer = (void *) &fh->key; *psize = sizeof(fh->key); }
9,613
C
.c
319
27.579937
78
0.685792
Seagate/cortx-fs
3
13
7
AGPL-3.0
9/7/2024, 2:18:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,882,688
cortxfs_xattr.c
Seagate_cortx-fs/src/cortxfs/cortxfs_xattr.c
/* * Filename: cortxfs_xattr.c * Description: CORTXFS file system XATTR interfaces * * Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * For any questions about this software or licensing, * please email [email protected] or [email protected]. */ #include <common/log.h> /* log_*() */ #include <common/helpers.h> /* RC_LABEL*() */ #include <cortxfs.h> /* cfs_* */ #include <dstore.h> /* dstore_oid_t */ #include <md_xattr.h> /* md_xattr_exists */ #include "cortxfs_internal.h" /*cfs_ino_to_oid */ #include <errno.h> /* ERANGE */ #include <string.h> /* memcpy */ #include <sys/xattr.h> /* XATTR_CREATE */ #include "kvtree.h" int cfs_setxattr(struct cfs_fs *cfs_fs, const cfs_cred_t *cred, const cfs_ino_t *ino, const char *name, char *value, size_t size, int flags) { int rc; dstore_oid_t oid; bool xattr_exists; dassert(cred && ino && name && value); if ((flags != XATTR_CREATE) && (flags != XATTR_REPLACE) && (flags != 0)) { rc = -EINVAL; goto out; } RC_WRAP_LABEL(rc, out, cfs_access, cfs_fs, cred, ino, CFS_ACCESS_WRITE); RC_WRAP_LABEL(rc, out, cfs_ino_to_oid, cfs_fs, ino, &oid); if ((flags == XATTR_CREATE) || (flags == XATTR_REPLACE)) { RC_WRAP_LABEL(rc, out, md_xattr_exists, &(cfs_fs->kvtree->index) , (obj_id_t *)&oid, name, &xattr_exists); if (flags == XATTR_CREATE && xattr_exists) { rc = -EEXIST; } else if (flags == XATTR_REPLACE && !xattr_exists) { rc = -ENOENT; } else { rc = 0; } if (rc != 0) { goto out; } } RC_WRAP_LABEL(rc, out, md_xattr_set, &(cfs_fs->kvtree->index), (obj_id_t *)&oid, name, value, size); out: log_trace("ctx=%p *ino=%llu oid=%" PRIx64 ":%" PRIx64 " rc=%d name=%s val=%p size=%lu", cfs_fs, *ino, oid.f_hi, oid.f_lo, rc, name, value, size); return rc; } size_t cfs_getxattr(struct cfs_fs *cfs_fs, cfs_cred_t *cred, const cfs_ino_t *ino, const char *name, char *value, size_t *size) { int rc; dstore_oid_t oid; void *read_val = NULL; size_t size_val; dassert(size != NULL); dassert(*size != 0); RC_WRAP_LABEL(rc, out, cfs_ino_to_oid, cfs_fs, ino, &oid); RC_WRAP_LABEL(rc, out, md_xattr_get, &(cfs_fs->kvtree->index), (obj_id_t *)&oid, name, &read_val, &size_val); /* The passed buffer size is insufficient to hold the xattr value */ if (*size < size_val) { rc = -ERANGE; goto out; } memcpy(value, read_val, size_val); *size = size_val; out: log_trace("ctx=%p *ino=%llu oid=%" PRIx64 ":%" PRIx64 " rc=%d name=%s" " val=%p size=%lu", cfs_fs, *ino, oid.f_hi, oid.f_lo, rc, name, read_val, size_val); if (read_val != NULL) { md_xattr_free(read_val); } return rc; } int cfs_removexattr(struct cfs_fs *cfs_fs, const cfs_cred_t *cred, const cfs_ino_t *ino, const char *name) { int rc; dstore_oid_t oid; RC_WRAP_LABEL(rc, out, cfs_access, cfs_fs, cred, ino, CFS_ACCESS_WRITE); RC_WRAP_LABEL(rc, out, cfs_ino_to_oid, cfs_fs, ino, &oid); RC_WRAP_LABEL(rc, out, md_xattr_delete, &(cfs_fs->kvtree->index), (obj_id_t *)&oid, name); out: log_trace("ctx=%p *ino=%llu oid=%" PRIx64 ":%" PRIx64 " rc=%d name=%s", cfs_fs, *ino, oid.f_hi, oid.f_lo, rc, name); return rc; } int cfs_remove_all_xattr(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *ino) { return 0; } int cfs_listxattr(struct cfs_fs *cfs_fs, const cfs_cred_t *cred, const cfs_ino_t *ino, void *buf, size_t *count, size_t *size) { int rc; dstore_oid_t oid; dassert(cred != NULL); dassert(ino != NULL); dassert(buf != NULL); dassert(count != NULL); dassert(size != NULL); RC_WRAP_LABEL(rc, out, cfs_access, cfs_fs, cred, ino, CFS_ACCESS_READ); RC_WRAP_LABEL(rc, out, cfs_ino_to_oid, cfs_fs, ino, &oid); RC_WRAP_LABEL(rc, out, md_xattr_list, &(cfs_fs->kvtree->index), (obj_id_t *)&oid, buf, count, size); out: log_trace("ctx=%p *ino=%llu oid=%" PRIx64 ":%" PRIx64 " rc=%d", cfs_fs, *ino, oid.f_hi, oid.f_lo, rc); return rc; }
4,672
C
.c
137
31.145985
88
0.649201
Seagate/cortx-fs
3
13
7
AGPL-3.0
9/7/2024, 2:18:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,882,689
cortxfs_fops.c
Seagate_cortx-fs/src/cortxfs/cortxfs_fops.c
/* * Filename: cortxfs_fops.c * Description: CORTXFS file system file operations * * Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * For any questions about this software or licensing, * please email [email protected] or [email protected]. */ #include <string.h> /* memset */ #include <kvstore.h> /* kvstore */ #include <dstore.h> /* dstore */ #include <cortxfs.h> /* cfs_access */ #include "cortxfs_fh.h" #include "cortxfs_internal.h" /* cfs_set_ino_oid */ #include <common/log.h> /* log_* */ #include <common/helpers.h> /* RC_* */ #include <sys/param.h> /* DEV_SIZE */ #include "kvtree.h" #include <errno.h> #include "operation.h" #include <cfs_perfc.h> int cfs_creat(struct cfs_fh *parent_fh, cfs_cred_t *cred, char *name, mode_t mode, cfs_ino_t *newfile_ino) { int rc; dstore_oid_t oid; cfs_ino_t child_ino = 0LL; cfs_ino_t *parent_ino = NULL; struct cfs_fs *cfs_fs = NULL; struct stat *parent_stat = NULL; struct dstore *dstore = dstore_get(); perfc_trace_inii(PFT_CFS_CREATE, PEM_CFS_TO_NFS); dassert(dstore && parent_fh && cred && name && newfile_ino); cfs_fs = cfs_fs_from_fh(parent_fh); parent_stat = cfs_fh_stat(parent_fh); parent_ino = cfs_fh_ino(parent_fh); RC_WRAP_LABEL(rc, out, cfs_access_check, cred, parent_stat, CFS_ACCESS_WRITE); /* Create tree entries, get new inode */ RC_WRAP_LABEL(rc, out, cfs_create_entry, parent_fh, cred, name, NULL, mode, &child_ino, CFS_FT_FILE); /* Get new unique extstore kfid */ RC_WRAP_LABEL(rc, out, dstore_get_new_objid, dstore, &oid); /* Set the ino-kfid key-val in kvs */ RC_WRAP_LABEL(rc, out, cfs_set_ino_oid, cfs_fs, &child_ino, &oid); /* Create the backend object with passed kfid */ RC_WRAP_LABEL(rc, out, dstore_obj_create, dstore, cfs_fs, &oid); *newfile_ino = child_ino; out: log_trace("parent_ino=%llu name=%s child_ino=%llu rc=%d", *parent_ino, name, child_ino, rc); perfc_trace_attr(PEA_CFS_CREATE_PARENT_INODE, *parent_ino); perfc_trace_attr(PEA_CFS_NEW_FILE_INODE, child_ino); perfc_trace_attr(PEA_CFS_RES_RC, rc); perfc_trace_finii(PERFC_TLS_POP_DONT_VERIFY); return rc; } int cfs_creat_ex(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *parent, char *name, mode_t mode, struct stat *stat_in, int stat_in_flags, cfs_ino_t *newfile, struct stat *stat_out) { int rc; cfs_ino_t child_ino = 0; struct cfs_fh *parent_fh = NULL; struct cfs_fh *child_fh = NULL; struct kvstore *kvstor = kvstore_get(); struct kvs_idx index; perfc_trace_inii(PFT_CFS_CREATE_EX, PEM_CFS_TO_NFS); dassert(kvstor && cfs_fs && parent && name && stat_in && newfile && stat_out); /* TODO:Temp_FH_op - to be removed * Should get rid of creating and destroying FH operation in this * API when caller pass the valid FH instead of inode number */ RC_WRAP_LABEL(rc, out, cfs_fh_from_ino, cfs_fs, parent, &parent_fh); index = cfs_fs->kvtree->index; /* NOTE: The following operations must be done within a single * transaction. */ RC_WRAP(kvs_begin_transaction, kvstor, &index); RC_WRAP_LABEL(rc, out, cfs_creat, parent_fh, cred, name, mode, &child_ino); RC_WRAP_LABEL(rc, cleanup, cfs_fh_from_ino, cfs_fs, &child_ino, &child_fh); RC_WRAP_LABEL(rc, cleanup, cfs_setattr, child_fh, cred, stat_in, stat_in_flags); memcpy(stat_out, cfs_fh_stat(child_fh), sizeof(struct stat)); RC_WRAP(kvs_end_transaction, kvstor, &index); *newfile = child_ino; child_ino = 0; cleanup: if (child_ino != 0) { /* We don't have transactions, so that let's just remove the * child_ino. */ (void) cfs_unlink2(parent_fh, child_fh, cred, name); (void) kvs_discard_transaction(kvstor, &index); log_err("cfs_fs=%p parent_ino=%llu child_ino=%llu name=%s rc=%d", cfs_fs, *parent, child_ino, name, rc); } out: if (child_fh != NULL) { cfs_fh_destroy_and_dump_stat(child_fh); } if (parent_fh != NULL) { cfs_fh_destroy_and_dump_stat(parent_fh); } log_debug("cfs_fs=%p parent_ino=%llu new_ino=%llu name=%s rc=%d", cfs_fs, *parent, rc==0 ? *newfile : child_ino, name, rc); perfc_trace_attr(PEA_CFS_RES_RC, rc); perfc_trace_finii(PERFC_TLS_POP_DONT_VERIFY); return rc; } static inline ssize_t __cfs_write(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_file_open_t *fd, void *buf, size_t count, off_t offset) { int rc; dstore_oid_t oid; struct stat *stat = NULL; struct cfs_fh *fh = NULL; struct dstore *dstore = dstore_get(); struct dstore_obj *obj = NULL; dassert(cfs_fs && cred && fd && buf); dassert(dstore); if (count == 0) { rc = 0; goto out; } /* TODO:Temp_FH_op - to be removed * Should get rid of creating and destroying FH operation in this * API when caller pass the valid FH instead of inode number */ RC_WRAP_LABEL(rc, out, cfs_fh_from_ino, cfs_fs, &fd->ino, &fh); stat = cfs_fh_stat(fh); RC_WRAP_LABEL(rc, out, cfs_ino_to_oid, cfs_fs, &fd->ino, &oid); RC_WRAP_LABEL(rc, out, cfs_access_check, cred, stat, CFS_ACCESS_WRITE); RC_WRAP_LABEL(rc, out, dstore_obj_open, dstore, &oid, &obj); RC_WRAP_LABEL(rc, out, dstore_pwrite, obj, offset, count, stat->st_blksize, (char *)buf); RC_WRAP_LABEL(rc, out, cfs_amend_stat, stat, STAT_MTIME_SET|STAT_CTIME_SET); if ((offset + count) > stat->st_size) { stat->st_size = offset + count; /* TODO: Check if DEV_BSIZE should be stat->st_blksize */ stat->st_blocks = (stat->st_size + DEV_BSIZE - 1) / DEV_BSIZE; } rc = count; out: if (obj != NULL) { dstore_obj_close(obj); } if (fh != NULL) { cfs_fh_destroy_and_dump_stat(fh); } log_trace("cfs_fs=%p ino=%llu fd=%p count=%lu offset=%ld rc=%d", cfs_fs, fd->ino, fd, count, (long)offset, rc); return rc; } ssize_t cfs_write(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_file_open_t *fd, void *buf, size_t count, off_t offset) { size_t rc; perfc_trace_inii(PFT_CFS_WRITE, PEM_CFS_TO_NFS); perfc_trace_attr(PEA_R_C_COUNT, count); perfc_trace_attr(PEA_R_C_OFFSET, offset); rc = __cfs_write(cfs_fs, cred, fd, buf, count, offset); perfc_trace_attr(PEA_R_C_RES_RC, rc); perfc_trace_finii(PERFC_TLS_POP_VERIFY); return rc; } int cfs_truncate(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *ino, struct stat *new_stat, int new_stat_flags) { int rc; dstore_oid_t oid; struct dstore *dstore = dstore_get(); struct dstore_obj *obj = NULL; struct cfs_fh *fh = NULL; struct stat *stat = NULL; size_t old_size; size_t new_size; dassert(ino && new_stat && dstore); dassert((new_stat_flags & STAT_SIZE_SET) != 0); /* TODO:Temp_FH_op - to be removed * Should get rid of creating and destroying FH operation in this * API when caller pass the valid FH instead of inode number */ RC_WRAP_LABEL(rc, out, cfs_fh_from_ino, cfs_fs, ino, &fh); stat = cfs_fh_stat(fh); old_size = stat->st_size; new_size = new_stat->st_size; /* TODO: Check if DEV_BSIZE should be stat->st_blksize */ new_stat->st_blocks = (new_size + DEV_BSIZE - 1) / DEV_BSIZE; /* If the caller wants to set mtime explicitly then * mtime and ctime will be different. Othewise, * we should keep them synchronous with each other. */ if ((new_stat_flags & STAT_MTIME_SET) == 0) { RC_WRAP_LABEL(rc, out, cfs_amend_stat, new_stat, STAT_MTIME_SET | STAT_CTIME_SET); new_stat_flags |= (STAT_MTIME_SET | STAT_CTIME_SET); } RC_WRAP_LABEL(rc, out, cfs_setattr, fh, cred, new_stat, new_stat_flags); RC_WRAP_LABEL(rc, out, cfs_ino_to_oid, cfs_fs, ino, &oid); RC_WRAP_LABEL(rc, out, dstore_obj_open, dstore, &oid, &obj); RC_WRAP_LABEL(rc, out, dstore_obj_resize, obj, old_size, new_size, stat->st_blksize); out: if (obj != NULL) { dstore_obj_close(obj); } if (fh != NULL) { cfs_fh_destroy_and_dump_stat(fh); } return rc; } static inline ssize_t __cfs_read(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_file_open_t *fd, void *buf, size_t count, off_t offset) { int rc; dstore_oid_t oid; size_t byte_to_read = count; struct stat *stat = NULL; struct cfs_fh *fh = NULL; struct dstore *dstore = dstore_get(); struct dstore_obj *obj = NULL; dassert(cfs_fs && cred && fd && buf); dassert(dstore); /* TODO:Temp_FH_op - to be removed * Should get rid of creating and destroying FH operation in this * API when caller pass the valid FH instead of inode number */ RC_WRAP_LABEL(rc, out, cfs_fh_from_ino, cfs_fs, &fd->ino, &fh); stat = cfs_fh_stat(fh); RC_WRAP_LABEL(rc, out, cfs_ino_to_oid, cfs_fs, &fd->ino, &oid); RC_WRAP_LABEL(rc, out, cfs_access_check, cred, stat, CFS_ACCESS_READ); /* Following are the cases which needs to be handled to ensure we are * not reading the data more than data written on file * 1. If file is empty( i.e: stat->st_size == 0) or count is zero * return immediately with data read = 0 * 2. If read offset is beyond/equal to the data written( i.e: * stat->st_size <= offset from where we are reading) then return * immediately with data read = 0. * 3.If amount of data to be read exceed the EOF( i.e: stat->st_size < * ( offset + buffer_size ) ) then read the only available data with * read_bytes = available bytes. * 4. Read is within the written data so read the requested data. */ if (stat->st_size == 0 || stat->st_size <= offset || byte_to_read == 0) { rc = 0; goto out; } else if (stat->st_size <= (offset + byte_to_read)) { /* Let's read only written bytes */ byte_to_read = stat->st_size - offset; } RC_WRAP_LABEL(rc, out, dstore_obj_open, dstore, &oid, &obj); RC_WRAP_LABEL(rc, out, dstore_pread, obj, offset, byte_to_read, stat->st_blksize, (char *)buf); RC_WRAP_LABEL(rc, out, cfs_amend_stat, stat, STAT_ATIME_SET); rc = byte_to_read; out: if (obj != NULL) { dstore_obj_close(obj); } if (fh != NULL) { cfs_fh_destroy_and_dump_stat(fh); } log_trace("cfs_fs=%p ino=%llu fd=%p count=%lu offset=%ld rc=%d", cfs_fs, fd->ino, fd, count, (long)offset, rc); return rc; } ssize_t cfs_read(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_file_open_t *fd, void *buf, size_t count, off_t offset) { size_t rc; perfc_trace_inii(PFT_CFS_READ, PEM_CFS_TO_NFS); perfc_trace_attr(PEA_R_C_COUNT, count); perfc_trace_attr(PEA_R_C_OFFSET, offset); rc = __cfs_read(cfs_fs, cred, fd, buf, count, offset); perfc_trace_attr(PEA_R_C_RES_RC, rc); perfc_trace_finii(PERFC_TLS_POP_VERIFY); return rc; }
11,037
C
.c
298
34.308725
79
0.680067
Seagate/cortx-fs
3
13
7
AGPL-3.0
9/7/2024, 2:18:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,882,690
cortxfs_ops.c
Seagate_cortx-fs/src/cortxfs/cortxfs_ops.c
/* * Filename: cortxfs_ops.c * Description: CORTXFS file system operations * * Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * For any questions about this software or licensing, * please email [email protected] or [email protected]. */ #include <common/log.h> /* log_debug() */ #include <kvstore.h> /* struct kvstore */ #include <cortxfs.h> /* cfs_get_stat() */ #include <debug.h> /* dassert() */ #include <common/helpers.h> /* RC_WRAP_LABEL() */ #include <limits.h> /* PATH_MAX */ #include <string.h> /* memcpy() */ #include <sys/time.h> /* gettimeofday() */ #include <errno.h> /* errno, -EINVAL */ #include <cortxfs_fh.h> /* cfs_fh */ #include "cortxfs_internal.h" /* dstore_obj_delete() */ #include <common.h> /* likely */ #include "kvtree.h" #include "operation.h" #include <cfs_perfc.h> static int cfs_detach2(struct cfs_fh *parent_fh, struct cfs_fh *child_fh, const cfs_cred_t *cred, const char *name); /* Internal cortxfs structure which holds the information given * by upper layer in case of readdir operation */ struct cfs_readdir_ctx { cfs_readdir_cb_t cb; void *ctx; }; struct stat *cfs_get_stat2(const struct kvnode *node) { uint16_t attr_size; struct stat *attr_buff = NULL; dassert(node); dassert(node->tree); dassert(node->basic_attr); attr_size = kvnode_get_basic_attr_buff(node, (void **)&attr_buff); dassert(attr_buff); dassert(attr_size == sizeof(struct stat)); log_trace("efs_get_stat2: " NODE_ID_F, NODE_ID_P(&node->node_id)); return attr_buff; } int cfs_set_stat(struct kvnode *node) { int rc; dassert(node); dassert(node->tree); dassert(node->basic_attr); rc = kvnode_dump(node); log_trace("efs_set_stat" NODE_ID_F "rc : %d", NODE_ID_P(&node->node_id), rc); return rc; } static inline int __cfs_getattr(struct cfs_fh *cfs_fh, struct stat *bufstat) { int rc = 0; struct stat *stat = NULL; dassert(cfs_fh && bufstat); stat = cfs_fh_stat(cfs_fh); if (stat == NULL) { rc = -1; } memcpy(bufstat, stat, sizeof(struct stat)); log_debug("ino=%d rc=%d", (int)bufstat->st_ino, rc); return rc; } int cfs_getattr(struct cfs_fh *cfs_fh, struct stat *bufstat) { size_t rc; perfc_trace_inii(PFT_CFS_GETATTR, PEM_CFS_TO_NFS); rc = __cfs_getattr(cfs_fh, bufstat); perfc_trace_attr(PEA_GETATTR_RES_RC, rc); perfc_trace_finii(PERFC_TLS_POP_DONT_VERIFY); return rc; } static inline int __cfs_setattr(struct cfs_fh *fh, cfs_cred_t *cred, struct stat *setstat, int statflag) { struct stat *stat = NULL; struct timeval t; mode_t ifmt; int rc; dassert(cred && setstat && fh); if (statflag == 0) { rc = 0; /* Nothing to do */ goto out; } rc = gettimeofday(&t, NULL); dassert(rc == 0); stat = cfs_fh_stat(fh); RC_WRAP_LABEL(rc, out, cfs_access_check, cred, stat, CFS_ACCESS_SETATTR); /* ctime is to be updated if md are changed */ stat->st_ctim.tv_sec = t.tv_sec; stat->st_ctim.tv_nsec = 1000 * t.tv_usec; if (statflag & STAT_MODE_SET) { ifmt = stat->st_mode & S_IFMT; stat->st_mode = setstat->st_mode | ifmt; } if (statflag & STAT_UID_SET) { stat->st_uid = setstat->st_uid; } if (statflag & STAT_GID_SET) { stat->st_gid = setstat->st_gid; } if (statflag & STAT_SIZE_SET) { stat->st_size = setstat->st_size; stat->st_blocks = setstat->st_blocks; } if (statflag & STAT_SIZE_ATTACH) { dassert(0); /* Unsupported */ } if (statflag & STAT_ATIME_SET) { stat->st_atim.tv_sec = setstat->st_atim.tv_sec; stat->st_atim.tv_nsec = setstat->st_atim.tv_nsec; } if (statflag & STAT_MTIME_SET) { stat->st_mtim.tv_sec = setstat->st_mtim.tv_sec; stat->st_mtim.tv_nsec = setstat->st_mtim.tv_nsec; } if (statflag & STAT_CTIME_SET) { stat->st_ctim.tv_sec = setstat->st_ctim.tv_sec; stat->st_ctim.tv_nsec = setstat->st_ctim.tv_nsec; } out: log_debug("rc=%d", rc); return rc; } int cfs_setattr(struct cfs_fh *fh, cfs_cred_t *cred, struct stat *setstat, int statflag) { size_t rc; perfc_trace_inii(PFT_CFS_SETATTR, PEM_CFS_TO_NFS); rc = __cfs_setattr(fh, cred, setstat, statflag); perfc_trace_attr(PEA_SETATTR_RES_RC, rc); perfc_trace_finii(PERFC_TLS_POP_DONT_VERIFY); return rc; } static int __cfs_access(struct cfs_fs *cfs_fs, const cfs_cred_t *cred, const cfs_ino_t *ino, int flags) { int rc = 0; struct stat *stat = NULL;; struct cfs_fh *fh = NULL; dassert(cred && ino); RC_WRAP_LABEL(rc, out, cfs_fh_from_ino, cfs_fs, ino, &fh); stat = cfs_fh_stat(fh); RC_WRAP_LABEL(rc, out, cfs_access_check, cred, stat, flags); out: return rc; } int cfs_access(struct cfs_fs *cfs_fs, const cfs_cred_t *cred, const cfs_ino_t *ino, int flags) { size_t rc; perfc_trace_inii(PFT_CFS_ACCESS, PEM_CFS_TO_NFS); perfc_trace_attr(PEA_ACCESS_FLAGS, flags); rc = __cfs_access(cfs_fs, cred, ino, flags); perfc_trace_attr(PEA_ACCESS_RES_RC, rc); perfc_trace_finii(PERFC_TLS_POP_DONT_VERIFY); return rc; } bool cfs_readdir_cb(void *cb_ctx, const char *name, const struct kvnode *node) { bool retval = false; struct cfs_readdir_ctx *cb_info = cb_ctx; cfs_ino_t child_inode; node_id_to_ino(&node->node_id, &child_inode); retval = cb_info->cb(cb_info->ctx, name, child_inode); log_trace("efs_readdir_cb:" NODE_ID_F ", retVal = %d", NODE_ID_P(&node->node_id), (int)retval); return retval; } static inline int __cfs_readdir(struct cfs_fs *cfs_fs, const cfs_cred_t *cred, const cfs_ino_t *dir_ino, cfs_readdir_cb_t cb, void *cb_ctx) { int rc; struct cfs_readdir_ctx cb_info = { .cb = cb, .ctx = cb_ctx}; struct cfs_fh *fh = NULL; struct stat *stat = NULL; node_id_t *node_id = NULL; /* TODO:Temp_FH_op - to be removed * Should get rid of creating and destroying FH operation in this * API when caller pass the valid FH instead of inode number */ RC_WRAP_LABEL(rc, out, cfs_fh_from_ino, cfs_fs, dir_ino, &fh); node_id = cfs_node_id_from_fh(fh); stat = cfs_fh_stat(fh); RC_WRAP_LABEL(rc, out, cfs_access_check, cred, stat, CFS_ACCESS_LIST_DIR); RC_WRAP_LABEL(rc, out, kvtree_iter_children, cfs_fs->kvtree, node_id, cfs_readdir_cb, &cb_info); RC_WRAP_LABEL(rc, out, cfs_amend_stat, stat, STAT_ATIME_SET); out: if (fh != NULL ) { cfs_fh_destroy_and_dump_stat(fh); } log_debug("cfs_fs=%p dir_ino=%llu rc=%d", cfs_fs, *dir_ino, rc); return rc; } int cfs_readdir(struct cfs_fs *cfs_fs, const cfs_cred_t *cred, const cfs_ino_t *dir_ino, cfs_readdir_cb_t cb, void *cb_ctx) { int rc; perfc_trace_inii(PFT_CFS_READDIR, PEM_CFS_TO_NFS); rc = __cfs_readdir(cfs_fs, cred, dir_ino, cb, cb_ctx); perfc_trace_finii(PERFC_TLS_POP_VERIFY); return rc; } static inline int __cfs_mkdir(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *parent, char *name, mode_t mode, cfs_ino_t *newdir) { int rc; dstore_oid_t oid; struct dstore *dstore = dstore_get(); struct cfs_fh *parent_fh = NULL; struct stat *parent_stat = NULL; dassert(dstore && cfs_fs && cred && parent && name && newdir); /* TODO:Temp_FH_op - to be removed * Should get rid of creating and destroying FH operation in this * API when caller pass the valid FH instead of inode number */ RC_WRAP_LABEL(rc, out, cfs_fh_from_ino, cfs_fs, parent, &parent_fh); parent_stat = cfs_fh_stat(parent_fh); RC_WRAP_LABEL(rc, out, cfs_access_check, cred, parent_stat, CFS_ACCESS_WRITE); RC_WRAP_LABEL(rc, out, cfs_create_entry, parent_fh, cred, name, NULL, mode, newdir, CFS_FT_DIR); /* Get a new unique oid */ RC_WRAP_LABEL(rc, out, dstore_get_new_objid, dstore, &oid); /* Set the ino-oid mapping for this directory in kvs.*/ RC_WRAP_LABEL(rc, out, cfs_set_ino_oid, cfs_fs, newdir, &oid); out: if (parent_fh != NULL) { cfs_fh_destroy_and_dump_stat(parent_fh); } log_trace("parent_ino=%llu name=%s newdir_ino=%llu mode=0x%X rc=%d", *parent, name, *newdir, mode, rc); return rc; } int cfs_mkdir(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *parent, char *name, mode_t mode, cfs_ino_t *newdir) { int rc; perfc_trace_inii(PFT_CFS_MKDIR, PEM_CFS_TO_NFS); rc = __cfs_mkdir(cfs_fs, cred, parent, name, mode, newdir); perfc_trace_finii(PERFC_TLS_POP_VERIFY); return rc; } int cfs_lookup(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *parent, char *name, cfs_ino_t *ino) { /* Porting notes: * This call is used by CORTXFS in many places so that it cannot be * direcly replaced by cfs_fh_lookup * without modifying them. * However, we should not have multiple versions of the same * file operation. There should be only one implementation * of lookup to make sure that we are testing/debugging * the right thing but not some old/deprecated thing. * So that, this function is modified to use cfs_fh * internally but it preserves the old interface. * Eventually the other code will slowly migrate to cortxfs_fh_lookup * and this code will be dissolved. */ int rc; struct cfs_fh *parent_fh = NULL; struct cfs_fh *fh = NULL; RC_WRAP_LABEL(rc, out, cfs_fh_from_ino, cfs_fs, parent, &parent_fh); RC_WRAP_LABEL(rc, out, cfs_fh_lookup, cred, parent_fh, name, &fh); *ino = *cfs_fh_ino(fh); out: if (parent_fh) { cfs_fh_destroy(parent_fh); } if (fh) { cfs_fh_destroy(fh); } return rc; } int cfs_readlink(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *lnk, char *content, size_t *size) { int rc; struct kvstore *kvstor = kvstore_get(); struct kvnode *node = NULL; struct cfs_fh *fh = NULL; struct stat *stat = NULL; buff_t value; dassert(cfs_fs && cred && lnk && size && content); dassert(*size != 0); buff_init(&value, NULL, 0); /* TODO:Temp_FH_op - to be removed * Should get rid of creating and destroying FH operation in this * API when caller pass the valid FH instead of inode number */ RC_WRAP_LABEL(rc, errfree, cfs_fh_from_ino, cfs_fs, lnk, &fh); stat = cfs_fh_stat(fh); node = cfs_kvnode_from_fh(fh); RC_WRAP_LABEL(rc, errfree, cfs_amend_stat, stat, STAT_ATIME_SET); /* Get symlink attributes */ RC_WRAP_LABEL(rc, errfree, cfs_get_sysattr, node, &value, CFS_SYS_ATTR_SYMLINK); dassert(value.len <= PATH_MAX); if (value.len > *size) { rc = -ENOBUFS; goto errfree; } memcpy(content, value.buf, value.len); *size = value.len; log_debug("Got link: content='%.*s'", (int) *size, content); errfree: if (fh != NULL) { cfs_fh_destroy_and_dump_stat(fh); } if (value.buf) { kvs_free(kvstor, value.buf); } log_trace("cfs_fs=%p: ino=%llu rc=%d", cfs_fs, *lnk, rc); return rc; } /** Default mode for a symlink object. * Here is a quote from `man 7 symlink`: * On Linux, the permissions of a symbolic link are not used in any * operations; the permissions are always 0777 (read, write, and execute * for all user categories), and can't be changed. */ #define CFS_SYMLINK_MODE 0777 int cfs_symlink(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *parent_ino, char *name, char *content, cfs_ino_t *newlnk_ino) { int rc; struct cfs_fh *parent_fh = NULL; struct stat *parent_stat = NULL; dassert(cfs_fs && cred && parent_ino && name && newlnk_ino && content); /* TODO:Temp_FH_op - to be removed * Should get rid of creating and destroying FH operation in this * API when caller pass the valid FH instead of inode number */ RC_WRAP_LABEL(rc, out, cfs_fh_from_ino, cfs_fs, parent_ino, &parent_fh); parent_stat = cfs_fh_stat(parent_fh); RC_WRAP_LABEL(rc, out, cfs_access_check, cred, parent_stat, CFS_ACCESS_WRITE); RC_WRAP_LABEL(rc, out, cfs_create_entry, parent_fh, cred, name, content, CFS_SYMLINK_MODE, newlnk_ino, CFS_FT_SYMLINK); out: if (parent_fh != NULL) { cfs_fh_destroy_and_dump_stat(parent_fh); } log_trace("parent_ino=%llu name=%s newlnk_ino=%llu content=%s rc=%d", *parent_ino, name, *newlnk_ino, content, rc); return rc; } int cfs_link(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *ino, cfs_ino_t *dino, char *dname) { int rc; str256_t k_name; struct kvstore *kvstor = kvstore_get(); struct kvs_idx index; struct cfs_fh *parent_fh = NULL; struct cfs_fh *child_fh = NULL; struct stat *parent_stat = NULL; struct stat *child_stat = NULL; node_id_t *dnode_id = NULL; node_id_t new_node_id; dassert(cred && ino && dname && dino && kvstor); index = cfs_fs->kvtree->index; RC_WRAP(kvs_begin_transaction, kvstor, &index); /* TODO:Temp_FH_op - to be removed * Should get rid of creating and destroying FH operation in this * API when caller pass the valid FH instead of inode number */ RC_WRAP_LABEL(rc, aborted, cfs_fh_from_ino, cfs_fs, dino, &parent_fh); dnode_id = cfs_node_id_from_fh(parent_fh); parent_stat = cfs_fh_stat(parent_fh); RC_WRAP_LABEL(rc, aborted, cfs_access_check, cred, parent_stat, CFS_ACCESS_WRITE); rc = cfs_fh_lookup(cred, parent_fh, dname, &child_fh); if (rc == 0) { rc = -EEXIST; goto aborted; } str256_from_cstr(k_name, dname, strlen(dname)); ino_to_node_id(ino, &new_node_id); RC_WRAP_LABEL(rc, aborted, kvtree_attach, cfs_fs->kvtree, dnode_id, &new_node_id, &k_name); RC_WRAP_LABEL(rc, aborted, cfs_fh_from_ino, cfs_fs, ino, &child_fh); child_stat = cfs_fh_stat(child_fh); RC_WRAP_LABEL(rc, aborted, cfs_amend_stat, child_stat, STAT_CTIME_SET|STAT_INCR_LINK); RC_WRAP_LABEL(rc, aborted, cfs_amend_stat, parent_stat, STAT_MTIME_SET|STAT_CTIME_SET); RC_WRAP(kvs_end_transaction, kvstor, &index); aborted: if (parent_fh != NULL) { cfs_fh_destroy_and_dump_stat(parent_fh); } if (child_fh != NULL ) { cfs_fh_destroy_and_dump_stat(child_fh); } if (rc != 0) { kvs_discard_transaction(kvstor, &index); } log_trace("cfs_fs=%p rc=%d ino=%llu dino=%llu dname=%s", cfs_fs, rc, *ino, *dino, dname); return rc; } static inline bool cfs_file_has_links(struct stat *stat) { return stat->st_nlink > 0; } static int cfs_destroy_orphaned_file2(struct cfs_fh *fh) { int rc; dstore_oid_t oid; cfs_ino_t *ino = NULL; struct cfs_fs *cfs_fs = NULL; struct stat *stat = NULL; struct kvnode *node = NULL; struct kvstore *kvstor = kvstore_get(); struct dstore *dstore = dstore_get(); struct kvs_idx index; dassert(kvstor && dstore && fh); cfs_fs = cfs_fs_from_fh(fh); ino = cfs_fh_ino(fh); stat = cfs_fh_stat(fh); index = cfs_fs->kvtree->index; if (cfs_file_has_links(stat)) { rc = 0; goto out; } kvs_begin_transaction(kvstor, &index); node = cfs_kvnode_from_fh(fh); RC_WRAP_LABEL(rc, out, cfs_del_stat, node); if (S_ISLNK(stat->st_mode)) { /* Delete symlink */ RC_WRAP_LABEL(rc, out, cfs_del_sysattr, node, CFS_SYS_ATTR_SYMLINK); } else if (S_ISREG(stat->st_mode)) { RC_WRAP_LABEL(rc, out, cfs_ino_to_oid, cfs_fs, ino, &oid); RC_WRAP_LABEL(rc, out, dstore_obj_delete, dstore, cfs_fs, &oid); RC_WRAP_LABEL(rc, out, cfs_del_oid, cfs_fs, ino); } else { /* Impossible: rmdir handles DIR; LNK and REG are handled by * this function, the other types cannot be created * at all. */ dassert(0); log_err("Attempt to remove unsupported object type (%d)", (int) stat->st_mode); } /* TODO: Delete File Xattrs here */ kvs_end_transaction(kvstor, &index); out: if (rc != 0) { kvs_discard_transaction(kvstor, &index); } log_trace("inode=%llu rc=%d", *ino, rc); return rc; } int cfs_destroy_orphaned_file(struct cfs_fs *cfs_fs, const cfs_ino_t *ino) { int rc; struct cfs_fh *fh = NULL; /* TODO:Temp_FH_op - to be removed * Should get rid of creating and destroying FH operation in this * API when caller pass the valid FH instead of inode number */ RC_WRAP_LABEL(rc, out, cfs_fh_from_ino, cfs_fs, ino, &fh); RC_WRAP_LABEL(rc, out, cfs_destroy_orphaned_file2, fh); out: if (fh != NULL) { cfs_fh_destroy(fh); } log_trace("inode=%llu rc=%d", *ino, rc); return rc; } /* TODO: Seems to be a huge fuction there needs to be a further investigation * to find out possibility of optimization and breaking down this APIs to * smaller APIs to improve readability */ int cfs_rename(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *sino_dir, char *sname, const cfs_ino_t *psrc, cfs_ino_t *dino_dir, char *dname, const cfs_ino_t *pdst, const struct cfs_rename_flags *pflags) { int rc; bool overwrite_dst = false; bool rename_inplace = false; bool is_dst_non_empty_dir = false; str256_t k_sname; str256_t k_dname; mode_t s_mode = 0; mode_t d_mode = 0; cfs_ino_t *sdir_ino = NULL; cfs_ino_t *ddir_ino = NULL; cfs_ino_t *dst_ino = NULL; node_id_t *sdir_id = NULL; node_id_t *ddir_id = NULL; node_id_t *src_id = NULL; node_id_t *dst_id = NULL; struct cfs_fh *sdir_fh = NULL; struct cfs_fh *ddir_fh = NULL; struct cfs_fh *src_fh = NULL; struct cfs_fh *dst_fh = NULL; struct stat *sdir_stat = NULL; struct stat *ddir_stat = NULL; struct stat *src_stat = NULL; struct stat *dst_stat = NULL; struct kvstore *kvstor = kvstore_get(); const struct cfs_rename_flags flags = pflags ? *pflags : (const struct cfs_rename_flags) CFS_RENAME_FLAGS_INIT; dassert(kvstor); dassert(cred); dassert(sino_dir && dino_dir); dassert(sname && dname); dassert(strlen(sname) <= NAME_MAX); dassert(strlen(dname) <= NAME_MAX); dassert((*sino_dir != *dino_dir || strcmp(sname, dname) != 0)); dassert(cfs_fs); /* TODO:Temp_FH_op - to be removed * Should get rid of creating and destroying FH operation in this * API when caller pass the valid FH instead of inode number */ RC_WRAP_LABEL(rc, out, cfs_fh_from_ino, cfs_fs, sino_dir, &sdir_fh); RC_WRAP_LABEL(rc, out, cfs_fh_from_ino, cfs_fs, dino_dir, &ddir_fh); sdir_ino = cfs_fh_ino(sdir_fh); sdir_stat = cfs_fh_stat(sdir_fh); sdir_id = cfs_node_id_from_fh(sdir_fh); ddir_ino = cfs_fh_ino(ddir_fh); ddir_stat = cfs_fh_stat(ddir_fh); ddir_id = cfs_node_id_from_fh(ddir_fh); rename_inplace = (*sdir_ino == *ddir_ino); RC_WRAP_LABEL(rc, out, cfs_access_check, cred, sdir_stat, CFS_ACCESS_DELETE_ENTITY); if (!rename_inplace) { RC_WRAP_LABEL(rc, out, cfs_access_check, cred, ddir_stat, CFS_ACCESS_CREATE_ENTITY); } RC_WRAP_LABEL(rc, out, cfs_fh_lookup, cred, sdir_fh, sname, &src_fh); src_stat = cfs_fh_stat(src_fh); src_id = cfs_node_id_from_fh(src_fh); /* Destination file/dir may or may not be present * based on lookup result we have to take descision */ rc = cfs_fh_lookup(cred, ddir_fh, dname, &dst_fh); if (rc < 0 && rc != -ENOENT) { goto out; } overwrite_dst = (rc != -ENOENT); if (overwrite_dst) { dst_ino = cfs_fh_ino(dst_fh); dst_stat = cfs_fh_stat(dst_fh); /* Fetch 'st_mode' for source and destination. */ s_mode = src_stat->st_mode; d_mode = dst_stat->st_mode; if (S_ISDIR(s_mode) != S_ISDIR(d_mode)) { log_warn("Incompatible source and destination %d,%d.", (int) s_mode, (int) d_mode); rc = -ENOTDIR; goto out; } if (S_ISDIR(d_mode)) { dst_id = cfs_node_id_from_fh(dst_fh); RC_WRAP_LABEL(rc, out, kvtree_has_children, cfs_fs->kvtree, dst_id, &is_dst_non_empty_dir); } if (is_dst_non_empty_dir) { log_warn("Destination is not empty (%llu:%s)", *dst_ino, dname); rc = -EEXIST; goto out; } if (S_ISDIR(d_mode)) { /* FIXME: rmdir() does not have an option to destroy * a dir object (unlinked from the tree), therefore * we might lose some data here if the following * operations (relinking) fail. */ RC_WRAP_LABEL(rc, out, cfs_rmdir, cfs_fs, cred, dino_dir, dname); } else { /* Make an ophaned file: it will be destoyed either * at the end of the function or when the file * will be closed. */ log_trace("Detaching a file from the tree " "(%llu, %llu, %s)", *dino_dir, *dst_ino, dname); RC_WRAP_LABEL(rc, out, cfs_detach2, ddir_fh, dst_fh, cred, dname); } } /* if (overwrite_dst) */ str256_from_cstr(k_sname, sname, strlen(sname)); str256_from_cstr(k_dname, dname, strlen(dname)); if (rename_inplace) { /* a shortcut for renaming only a dentry * without re-linking of the inodes. */ RC_WRAP_LABEL(rc, out, cfs_tree_rename_link, sdir_fh, src_fh, &k_sname, &k_dname); } else { s_mode = src_stat->st_mode; RC_WRAP_LABEL(rc, out, kvtree_detach, cfs_fs->kvtree, sdir_id, &k_sname); RC_WRAP_LABEL(rc, out, kvtree_attach, cfs_fs->kvtree, ddir_id, src_id, &k_dname); if (S_ISDIR(s_mode)) { RC_WRAP_LABEL(rc, out, cfs_amend_stat, sdir_stat, STAT_DECR_LINK); RC_WRAP_LABEL(rc, out, cfs_amend_stat, ddir_stat, STAT_INCR_LINK); } } if (overwrite_dst && !S_ISDIR(d_mode) && !flags.is_dst_open) { /* Remove the actual 'destination' object only if all * previous operations have completed successfully. */ log_trace("Removing detached file (%llu)", *dst_ino); RC_WRAP_LABEL(rc, out, cfs_destroy_orphaned_file2, dst_fh); } out: if (sdir_fh) { cfs_fh_destroy_and_dump_stat(sdir_fh); } if (ddir_fh) { cfs_fh_destroy_and_dump_stat(ddir_fh); } if (src_fh) { cfs_fh_destroy_and_dump_stat(src_fh); } if (dst_fh) { cfs_fh_destroy(dst_fh); } log_debug("cfs_fs=%p sdir_ino=%llu ddir_ino=%llu src_ino=%llu" "sname=%s dst_ino=%llu dname=%s rc=%d",cfs_fs, *sino_dir, *dino_dir, psrc?*psrc:0LL, sname, pdst?*pdst:0LL, dname, rc); return rc; } static inline int __cfs_rmdir(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *parent_ino, char *name) { int rc; bool is_non_empty_dir; str256_t kname; struct kvstore *kvstor = kvstore_get(); struct kvs_idx index; struct cfs_fh *parent_fh = NULL; struct cfs_fh *child_fh = NULL; struct stat *parent_stat = NULL; struct kvnode *child_node = NULL; struct kvnode *parent_node = NULL; cfs_ino_t *child_ino = NULL; node_id_t *cnode_id = NULL; node_id_t *pnode_id = NULL; dassert(cfs_fs && cred && parent_ino && name && kvstor); dassert(strlen(name) <= NAME_MAX); index = cfs_fs->kvtree->index; /* TODO:Temp_FH_op - to be removed * Should get rid of creating and destroying FH operation in this * API when caller pass the valid FH instead of inode number */ RC_WRAP_LABEL(rc, out, cfs_fh_from_ino, cfs_fs, parent_ino, &parent_fh); parent_stat = cfs_fh_stat(parent_fh); RC_WRAP_LABEL(rc, out, cfs_access_check, cred, parent_stat, CFS_ACCESS_WRITE); RC_WRAP_LABEL(rc, out, cfs_fh_lookup, cred, parent_fh, name, &child_fh); child_ino = cfs_fh_ino(child_fh); cnode_id = cfs_node_id_from_fh(child_fh); /* Check if directory empty */ RC_WRAP_LABEL(rc, out, kvtree_has_children, cfs_fs->kvtree, cnode_id, &is_non_empty_dir); if (is_non_empty_dir) { rc = -ENOTEMPTY; log_debug("cfs_fs=%p parent_ino=%llu child_ino=%llu name=%s" " not empty", cfs_fs, *parent_ino, *child_ino, name); goto out; } RC_WRAP_LABEL(rc, out, kvs_begin_transaction, kvstor, &index); str256_from_cstr(kname, name, strlen(name)); /* Detach the inode */ pnode_id = cfs_node_id_from_fh(parent_fh); RC_WRAP_LABEL(rc, aborted, kvtree_detach, cfs_fs->kvtree, pnode_id, &kname); /* Remove its stat */ child_node = cfs_kvnode_from_fh(child_fh); RC_WRAP_LABEL(rc, aborted, cfs_del_stat, child_node); /* Child dir has a "hardlink" to the parent ("..") */ parent_node = cfs_kvnode_from_fh(parent_fh); RC_WRAP_LABEL(rc, aborted, cfs_update_stat, parent_node, STAT_DECR_LINK|STAT_MTIME_SET|STAT_CTIME_SET); RC_WRAP_LABEL(rc, aborted, cfs_del_oid, cfs_fs, child_ino); /* TODO: Remove all xattrs when cortxfs_remove_all_xattr is implemented */ RC_WRAP_LABEL(rc, out, kvs_end_transaction, kvstor, &index); aborted: if (rc < 0) { /* FIXME: error code is overwritten */ RC_WRAP_LABEL(rc, out, kvs_discard_transaction, kvstor, &index); } out: if (parent_fh != NULL) { cfs_fh_destroy_and_dump_stat(parent_fh); } if (child_fh != NULL) { cfs_fh_destroy(child_fh); } log_debug("cfs_fs=%p parent_ino=%llu child_ino=%llu name=%s rc=%d", cfs_fs, *parent_ino, child_ino ? *child_ino : 0LL, name, rc); return rc; } int cfs_rmdir(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *parent, char *name) { int rc; perfc_trace_inii(PFT_CFS_RMDIR, PEM_CFS_TO_NFS); rc = __cfs_rmdir(cfs_fs, cred, parent, name); perfc_trace_finii(PERFC_TLS_POP_VERIFY); return rc; } int cfs_unlink2(struct cfs_fh *parent_fh, struct cfs_fh *child_fh, cfs_cred_t *cred, char *name) { int rc; dassert(parent_fh && child_fh && cred && name); dassert(cfs_fh_invariant(parent_fh)); dassert(cfs_fh_invariant(child_fh)); RC_WRAP_LABEL(rc, out, cfs_detach2, parent_fh, child_fh, cred, name); RC_WRAP_LABEL(rc, out, cfs_destroy_orphaned_file2, child_fh); out: log_debug("cfs_fs=%p parent_ino=%llu child_ino=%llu name=%s rc=%d", cfs_fs_from_fh(parent_fh), *cfs_fh_ino(parent_fh), *cfs_fh_ino(child_fh), name, rc); return rc; } int cfs_unlink(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *dir, cfs_ino_t *fino, char *name) { int rc; cfs_ino_t child_ino = 0LL; struct stat *child_stat = NULL; struct cfs_fh *child_fh = NULL; struct cfs_fh *parent_fh = NULL; dassert(cfs_fs && cred && dir && name); /* TODO:Temp_FH_op - to be removed * Should get rid of creating and destroying FH operation in this * API when caller pass the valid FH instead of inode number */ RC_WRAP_LABEL(rc, out, cfs_fh_from_ino, cfs_fs, dir, &parent_fh); if (likely(fino != NULL)) { RC_WRAP_LABEL(rc, out, cfs_fh_from_ino, cfs_fs, fino, &child_fh); child_ino = *fino; } else { RC_WRAP_LABEL(rc, out, cfs_fh_lookup, cred, parent_fh, name, &child_fh); child_ino = *cfs_fh_ino(child_fh); } child_stat = cfs_fh_stat(child_fh); RC_WRAP_LABEL(rc, out, cfs_unlink2, parent_fh, child_fh, cred, name); out: if (parent_fh != NULL) { cfs_fh_destroy_and_dump_stat(parent_fh); } if (child_fh != NULL) { dassert(child_stat); if (cfs_file_has_links(child_stat)) { cfs_fh_destroy_and_dump_stat(child_fh); } else { cfs_fh_destroy(child_fh); } } log_debug("cfs_fs=%p parent_ino=%llu child_ino=%llu name=%s rc=%d", cfs_fs, *dir, child_ino, name, rc); return rc; } static int cfs_detach2(struct cfs_fh *parent_fh, struct cfs_fh *child_fh, const cfs_cred_t *cred, const char *name) { int rc; str256_t k_name; struct kvs_idx index; struct kvstore *kvstor = kvstore_get(); struct cfs_fs *cfs_fs = NULL; struct stat *parent_stat = NULL; struct stat *child_stat = NULL; node_id_t *pnode_id = NULL; dassert(kvstor && parent_fh && cred && child_fh && name); cfs_fs = cfs_fs_from_fh(parent_fh); index = cfs_fs->kvtree->index; kvs_begin_transaction(kvstor, &index); parent_stat = cfs_fh_stat(parent_fh); child_stat = cfs_fh_stat(child_fh); RC_WRAP_LABEL(rc, out, cfs_access_check, cred, parent_stat, CFS_ACCESS_DELETE_ENTITY); pnode_id = cfs_node_id_from_fh(parent_fh); str256_from_cstr(k_name, name, strlen(name)); RC_WRAP_LABEL(rc, out, kvtree_detach, cfs_fs->kvtree, pnode_id, &k_name); RC_WRAP_LABEL(rc, out, cfs_amend_stat, child_stat, STAT_CTIME_SET|STAT_DECR_LINK); RC_WRAP_LABEL(rc, out, cfs_amend_stat, parent_stat, STAT_CTIME_SET|STAT_MTIME_SET); kvs_end_transaction(kvstor, &index); out: if (rc != 0) { kvs_discard_transaction(kvstor, &index); } log_trace("cfs_fs=%p parent_ino=%llu name=%s child_ino=%llu rc=%d", cfs_fs, (unsigned long long int)parent_stat->st_ino, name, (unsigned long long int)child_stat->st_ino, rc); return rc; } int cfs_detach(struct cfs_fs *cfs_fs, const cfs_cred_t *cred, const cfs_ino_t *parent_ino, const cfs_ino_t *child_ino, const char *name) { int rc; struct cfs_fh *parent_fh = NULL; struct cfs_fh *child_fh = NULL; /* TODO:Temp_FH_op - to be removed * Should get rid of creating and destroying FH operation in this * API when caller pass the valid FH instead of inode number */ RC_WRAP_LABEL(rc, out, cfs_fh_from_ino, cfs_fs, parent_ino, &parent_fh); RC_WRAP_LABEL(rc, out, cfs_fh_from_ino, cfs_fs, child_ino, &child_fh); RC_WRAP_LABEL(rc, out, cfs_detach2, parent_fh, child_fh, cred, name); out: if (parent_fh != NULL) { cfs_fh_destroy_and_dump_stat(parent_fh); } if (child_fh != NULL) { cfs_fh_destroy_and_dump_stat(child_fh); } log_trace("cfs_fs=%p parent_ino=%llu name=%s child_ino=%llu rc=%d", cfs_fs, *parent_ino, name, *child_ino, rc); return rc; }
29,128
C
.c
861
30.768873
79
0.673014
Seagate/cortx-fs
3
13
7
AGPL-3.0
9/7/2024, 2:18:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,882,691
cortxfs_internal.c
Seagate_cortx-fs/src/cortxfs/cortxfs_internal.c
/* * Filename: cortxfs_internal.c * Description: CORTXFS file system internal APIs * * Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * For any questions about this software or licensing, * please email [email protected] or [email protected]. */ #include <stdio.h> #include <errno.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <limits.h> /* PATH_MAX */ #include <sys/time.h> #include <ini_config.h> #include <common/log.h> #include <common/helpers.h> #include "cortxfs.h" #include "cortxfs_fh.h" #include "cortxfs_internal.h" #include <dstore.h> #include <debug.h> #include <common.h> /* likely */ #include <inttypes.h> /* PRIx64 */ #include "kvtree.h" #include "kvnode.h" static int cfs_set_ino_no_gen(struct cfs_fs *cfs_fs, cfs_ino_t ino); static int cfs_get_ino_no_gen(struct cfs_fs *cfs_fs, cfs_ino_t *ino); static int cfs_del_ino_no_gen(struct cfs_fs *cfs_fs); /** Get pointer to a const C-string owned by cortxfs_name string. */ static inline const char *cfs_name_as_cstr(const str256_t *kname) { return kname->s_str; } static inline const char *cfs_key_type_to_str(cfs_key_type_t ktype) { switch (ktype) { case CFS_KEY_TYPE_DIRENT: return "dentry"; case CFS_KEY_TYPE_PARENT: return "parentdir"; case CFS_KEY_TYPE_STAT: return "stat"; case CFS_KEY_TYPE_SYMLINK: return "link"; case CFS_KEY_TYPE_INODE_KFID: return "oid"; case CFS_KEY_TYPE_GI_INDEX: /* @todo remove when default fs is gone */ return "index"; case CFS_KEY_TYPE_FS_ID_FID: return "fid"; case CFS_KEY_TYPE_FS_NAME: return "fsid"; case CFS_KEY_TYPE_FS_ID: return "fsname"; case CFS_KEY_TYPE_FS_ID_NEXT: return "fsidnext"; case CFS_KEY_TYPE_INO_NUM_GEN: return "ino_counter"; case CFS_KEY_TYPE_INVALID: return "<invalid>"; } dassert(0); return "<fail>"; } #define INODE_ATTR_KEY_INIT(__kfid, __ktype) \ { \ .fid = __kfid, \ .md = { \ .type = __ktype, \ .version = CFS_VERSION_0, \ }, \ } /* @todo rename this to INODE_ATTR_KEY_INIT once all the instances of * INODE_ATTR_KEY_INIT are replaced with INODE_ATTR_KEY_PTR_INIT */ #define INODE_ATTR_KEY_PTR_INIT(_key, _ino, _ktype) \ { \ _key->fid.f_hi = (*_ino), \ _key->fid.f_lo = 0, \ _key->md.type = _ktype, \ _key->md.version = CFS_VERSION_0; \ } /* Access routines */ int cfs_access_check(const cfs_cred_t *cred, const struct stat *stat, int flags) { int check = 0; int i, grp_count; bool grp_match = false; if (!stat || !cred) return -EINVAL; /* Root's superpowers */ if (cred->uid == CFS_ROOT_UID) return 0; /* Check for matching group in group list */ grp_count = (cred->total_grps <= CORTXFS_CRED_GRPS) ? \ cred->total_grps : CORTXFS_CRED_GRPS; for (i = 0; i < grp_count; i++) { if (cred->grp_list[i] == stat->st_gid) { grp_match = true; break; } } if (cred->uid == stat->st_uid) { /* skip access check of owner for set attribute.*/ if(flags & CFS_ACCESS_SETATTR) return 0; if (flags & CFS_ACCESS_READ) check |= STAT_OWNER_READ; if (flags & CFS_ACCESS_WRITE) check |= STAT_OWNER_WRITE; if (flags & CFS_ACCESS_EXEC) check |= STAT_OWNER_EXEC; } else if ( grp_match || (cred->gid == stat->st_gid)) { if (flags & CFS_ACCESS_READ) check |= STAT_GROUP_READ; if (flags & CFS_ACCESS_WRITE) check |= STAT_GROUP_WRITE; if (flags & CFS_ACCESS_EXEC) check |= STAT_GROUP_EXEC; } else { if (flags & CFS_ACCESS_READ) check |= STAT_OTHER_READ; if (flags & CFS_ACCESS_WRITE) check |= STAT_OTHER_WRITE; if (flags & CFS_ACCESS_EXEC) check |= STAT_OTHER_EXEC; } if ((check & stat->st_mode) != check) return -EPERM; else return 0; /* Should not be reached */ return -EPERM; } static int cfs_set_ino_no_gen(struct cfs_fs *cfs_fs, cfs_ino_t ino) { int rc; buff_t value; dassert(cfs_fs != NULL); buff_init(&value, &ino, sizeof (ino)); RC_WRAP_LABEL(rc, out, cfs_set_sysattr, cfs_fs->root_node, value, CFS_SYS_ATTR_INO_NUM_GEN); out: log_trace("cfs_set_ino_no_gen() ends, ino:%llu, rc:%d", ino, rc); return rc; } static int cfs_get_ino_no_gen(struct cfs_fs *cfs_fs, cfs_ino_t *ino) { int rc; buff_t value; dassert(cfs_fs != NULL); dassert(ino != NULL); buff_init(&value, NULL, 0); RC_WRAP_LABEL(rc, out, cfs_get_sysattr, cfs_fs->root_node, &value, CFS_SYS_ATTR_INO_NUM_GEN); if (sizeof (*ino) != value.len) { log_trace("invalid value size %zu, expected %zu", value.len, sizeof (*ino)); goto out; } memcpy(ino, value.buf, sizeof (*ino)); out: log_trace("cfs_get_ino_no_gen() ends, ino:%llu, rc:%d", *ino, rc); if (value.buf) { free(value.buf); } return rc; } static int cfs_del_ino_no_gen(struct cfs_fs *cfs_fs) { int rc; dassert(cfs_fs != NULL); RC_WRAP_LABEL(rc, out, cfs_del_sysattr, cfs_fs->root_node, CFS_SYS_ATTR_INO_NUM_GEN); out: log_trace("cfs_del_ino_no_gen() ends, rc:%d", rc); return rc; } int cfs_kvnode_init(struct kvnode *node, struct kvtree *tree, const cfs_ino_t *ino, const struct stat *bufstat) { int rc; node_id_t node_id; uint16_t size = sizeof(struct stat); dassert(tree); dassert(bufstat); /** * A kvnode is identified by a 128 bit node id. However, currently cortxfs * uses 64 bit inodes in it's apis to identify the entities. The * following api is a temporary arrangement to convert 64 bit inodes * to 128 bit node ids. * @TODO: Cleanup these when cortxfs filehandle (or equivalent) is * implemented. The filehandles would eventually use 128bit unique fids. */ ino_to_node_id(ino, &node_id); rc = kvnode_init(tree, &node_id, (void *)bufstat, size, node); log_trace("cfs_kvnode_init: " NODE_ID_F "uid: %d, gid: %d, mode: %04o," " rc : %d", NODE_ID_P(&node->node_id), bufstat->st_uid, bufstat->st_gid, bufstat->st_mode & 07777, rc); return rc; } int cfs_kvnode_load(struct kvnode *node, struct kvtree *tree, const cfs_ino_t *ino) { int rc; node_id_t node_id; dassert(tree); /** * A kvnode is identified by a 128 bit node id. However, currently cortxfs * uses 64 bit inodes in it's apis to identify the entities. The * following api is a temporary arrangement to convert 64 bit inodes * to 128 bit node ids. * @TODO: Cleanup these when cortxfs filehandle (or equivalent) is * implemented. The filehandles would eventually use 128bit unique fids. */ ino_to_node_id(ino, &node_id); rc = kvnode_load(tree, &node_id, node); log_trace("cfs_load_kvnode: " NODE_ID_F " rc : %d", NODE_ID_P(&node->node_id), rc); return rc; } int cfs_get_stat(const struct kvnode *node, struct stat **bufstat) { int rc = 0; uint16_t attr_size; struct stat *attr_buff = NULL; struct kvstore *kvstore = kvstore_get(); dassert(node); dassert(node->tree); dassert(node->basic_attr); attr_size = kvnode_get_basic_attr_buff(node, (void **)&attr_buff); dassert(attr_buff); dassert(attr_size == sizeof(struct stat)); /* TODO: Can we avoid kvs_alloc and have separate API for cortxfs? */ RC_WRAP_LABEL(rc, out, kvs_alloc, kvstore, (void **)bufstat, attr_size); /* TODO: This extra memcpy is here because the lifetime of kvnode is * limited by the scope of this function. When kvnode will be promoted * upper to the argument list then we can return a weak reference to its * internals (instead of loading kvsnode from kvstore). But right now we * cannot do that, so that we just allocate a new buffer, copy data * there and return this buffer to the caller */ memcpy(*bufstat, attr_buff, attr_size); out: log_trace("cfs_get_stat: " NODE_ID_F " rc : %d", NODE_ID_P(&node->node_id), rc); return rc; } int cfs_del_stat(struct kvnode *node) { int rc; dassert(node); dassert(node->tree); dassert(node->basic_attr); rc = kvnode_delete(node); log_trace("cfs_del_stat: " NODE_ID_F " rc : %d", NODE_ID_P(&node->node_id), rc); return rc; } int cfs_amend_stat(struct stat *stat, int flags) { struct timeval t; int rc = 0; dassert(stat); rc = gettimeofday(&t, NULL); dassert(rc == 0); if (flags & STAT_ATIME_SET) { stat->st_atim.tv_sec = t.tv_sec; stat->st_atim.tv_nsec = 1000 * t.tv_usec; } if (flags & STAT_MTIME_SET) { stat->st_mtim.tv_sec = t.tv_sec; stat->st_mtim.tv_nsec = 1000 * t.tv_usec; } if (flags & STAT_CTIME_SET) { stat->st_ctim.tv_sec = t.tv_sec; stat->st_ctim.tv_nsec = 1000 * t.tv_usec; } if (flags & STAT_INCR_LINK) { /* nlink_t has to be an unsigned type, so overflow checking is * simple. */ if (unlikely(stat->st_nlink + 1 == 0)) { rc = RC_WRAP_SET(-EINVAL); goto out; } if (unlikely(stat->st_nlink == CFS_MAX_LINK)) { rc = RC_WRAP_SET(-EINVAL); goto out; } stat->st_nlink += 1; } if (flags & STAT_DECR_LINK) { if (unlikely(stat->st_nlink == 0)) { rc = RC_WRAP_SET(-EINVAL); goto out; } stat->st_nlink -= 1; } out: return rc; } int cfs_update_stat(struct kvnode *node, int flags) { int rc; uint16_t stat_size; struct stat *stat = NULL; stat_size = kvnode_get_basic_attr_buff(node, (void **)&stat); dassert(stat); dassert(stat_size == sizeof(struct stat)); RC_WRAP_LABEL(rc, out, cfs_amend_stat, stat, flags); RC_WRAP_LABEL(rc, out, cfs_set_stat, node); out: log_trace("cfs_update_stat (%d) for " NODE_ID_F ", rc=%d", flags, NODE_ID_P(&node->node_id), rc); return rc; } int cfs_set_sysattr(const struct kvnode *node, const buff_t value, enum cfs_sys_attr_type attr_type) { int rc; rc = kvnode_set_sys_attr(node, attr_type, value); log_trace("cfs_set_sysattr:" OBJ_ID_F ", rc = %d", OBJ_ID_P(&node->node_id), rc); return rc; } int cfs_get_sysattr(const struct kvnode *node, buff_t *value, enum cfs_sys_attr_type attr_type) { int rc; rc = kvnode_get_sys_attr(node, attr_type, value); log_trace("cfs_get_sysattr:" OBJ_ID_F ", rc = %d", OBJ_ID_P(&node->node_id), rc); return rc; } int cfs_del_sysattr(const struct kvnode *node, enum cfs_sys_attr_type attr_type) { int rc; rc = kvnode_del_sys_attr(node, attr_type); log_trace("cfs_del_sysattr:" OBJ_ID_F ", rc = %d", OBJ_ID_P(&node->node_id), rc); return rc; } int cfs_ino_num_gen_init(struct cfs_fs *cfs_fs) { int rc; dassert(cfs_fs != NULL); rc = cfs_set_ino_no_gen(cfs_fs, CFS_ROOT_INODE_NUM_GEN_START); log_trace("cfs_ino_num_gen_init() ends, rc:%d", rc); return rc; } int cfs_ino_num_gen_fini(struct cfs_fs *cfs_fs) { int rc; dassert(cfs_fs != NULL); rc = cfs_del_ino_no_gen(cfs_fs); log_trace("cfs_ino_num_gen_fini() ends, rc:%d", rc); return rc; } int cfs_tree_rename_link(struct cfs_fh *parent_fh, struct cfs_fh *child_fh, const str256_t *old_name, const str256_t *new_name) { int rc; struct kvstore *kvstor = kvstore_get(); struct kvs_idx index; struct stat *parent_stat = NULL; struct cfs_fs *cfs_fs = NULL; node_id_t *cnode_id = NULL; node_id_t *pnode_id = NULL; dassert(kvstor && parent_fh && child_fh && old_name && new_name); cfs_fs = cfs_fs_from_fh(parent_fh); index = cfs_fs->kvtree->index; pnode_id = cfs_node_id_from_fh(parent_fh); /* The caller must ensure that the entry exists prior renaming */ dassert(kvtree_lookup(cfs_fs->kvtree, pnode_id, old_name, NULL) == 0); RC_WRAP_LABEL(rc, out, kvtree_detach, cfs_fs->kvtree, pnode_id, old_name); cnode_id = cfs_node_id_from_fh(child_fh); RC_WRAP_LABEL(rc, out, kvtree_attach, cfs_fs->kvtree, pnode_id, cnode_id, new_name); // Update ctime stat parent_stat = cfs_fh_stat(parent_fh); RC_WRAP_LABEL(rc, out, cfs_amend_stat, parent_stat, STAT_CTIME_SET); out: log_debug("(%p,pino=%llu,ino=%llu,o=%.*s,n=%.*s) = %d", cfs_fs, *cfs_fh_ino(parent_fh), *cfs_fh_ino(child_fh), old_name->s_len, old_name->s_str, new_name->s_len, new_name->s_str, rc); return rc; } static int cfs_create_check_name(const char *name, size_t len) { int rc = 0; const char *parent = ".."; if (len > NAME_MAX) { log_debug("Name too long %s", name); rc = -E2BIG; goto out; } if (len == 1 && (name[0] == '.' || name[0] == '/')) { log_debug("File already exists: %s", name); rc = -EEXIST; goto out; } if (len == 2 && (strncmp(name, parent, 2) == 0)) { log_debug("File already exists: %s", name); rc = -EEXIST; goto out; } out: return rc; } int cfs_next_inode(struct cfs_fs *cfs_fs, cfs_ino_t *ino_out) { int rc; cfs_ino_t ino; dassert(cfs_fs != NULL); dassert(ino_out != NULL); RC_WRAP_LABEL(rc, out, cfs_get_ino_no_gen, cfs_fs, &ino); ino++; RC_WRAP_LABEL(rc, out, cfs_set_ino_no_gen, cfs_fs, ino); *ino_out = ino; out: log_trace("cfs_next_inode() ends, ino = %llu, rc:%d", *ino_out, rc); return rc; } int cfs_create_entry(struct cfs_fh *parent_fh, cfs_cred_t *cred, char *name, char *lnk, mode_t mode, cfs_ino_t *new_entry, enum cfs_file_type type) { int rc; int flags; struct stat bufstat; struct timeval t; size_t namelen; struct cfs_fs *cfs_fs = cfs_fs_from_fh(parent_fh); struct kvstore *kvstor = kvstore_get(); struct kvs_idx index = cfs_fs->kvtree->index; struct kvnode new_node = KVNODE_INIT_EMTPY; struct stat *parent_stat = NULL; struct cfs_fh *fh = NULL; str256_t k_name; node_id_t new_node_id, parent_node_id; dassert(kvstor); parent_stat = cfs_fh_stat(parent_fh); namelen = strlen(name); if (namelen == 0) { rc = -EINVAL; goto out; } /* check if name is not '.' or '..' or '/' */ RC_WRAP_LABEL(rc, out, cfs_create_check_name, name, namelen); if ((type == CFS_FT_SYMLINK) && (lnk == NULL)) { rc = -EINVAL; goto out; } /* Return if file/dir/symlink already exists. */ rc = cfs_fh_lookup(cred, parent_fh, name, &fh); if (rc == 0) { rc = -EEXIST; goto out; } RC_WRAP_LABEL(rc, out, cfs_next_inode, cfs_fs, new_entry); RC_WRAP_LABEL(rc, out, kvs_begin_transaction, kvstor, &index); str256_from_cstr(k_name, name, strlen(name)); ino_to_node_id(new_entry, &new_node_id); ino_to_node_id((cfs_ino_t *)&parent_stat->st_ino, &parent_node_id); RC_WRAP_LABEL(rc, errfree, kvtree_attach, cfs_fs->kvtree, &parent_node_id, &new_node_id, &k_name); if (gettimeofday(&t, NULL) != 0) { rc = -EPERM; goto errfree; } /* Set the stats of the new file */ memset(&bufstat, 0, sizeof(struct stat)); bufstat.st_uid = cred->uid; bufstat.st_gid = cred->gid; bufstat.st_ino = *new_entry; bufstat.st_atim.tv_sec = t.tv_sec; bufstat.st_atim.tv_nsec = 1000 * t.tv_usec; bufstat.st_mtim.tv_sec = bufstat.st_atim.tv_sec; bufstat.st_mtim.tv_nsec = bufstat.st_atim.tv_nsec; bufstat.st_ctim.tv_sec = bufstat.st_atim.tv_sec; bufstat.st_ctim.tv_nsec = bufstat.st_atim.tv_nsec; bufstat.st_blksize = parent_stat->st_blksize; switch (type) { case CFS_FT_DIR: bufstat.st_mode = S_IFDIR | mode; bufstat.st_nlink = 2; break; case CFS_FT_FILE: bufstat.st_mode = S_IFREG | mode; bufstat.st_nlink = 1; break; case CFS_FT_SYMLINK: bufstat.st_mode = S_IFLNK | mode; bufstat.st_nlink = 1; break; default: /* Should never happen */ dassert(0); /* Handle error, since dasserts can be disabled in release */ rc = -EINVAL; goto errfree; } /* Create node for new entry and set its stats */ RC_WRAP_LABEL(rc, errfree, cfs_kvnode_init, &new_node, cfs_fs->kvtree, new_entry, &bufstat); RC_WRAP_LABEL(rc, errfree, cfs_set_stat, &new_node); if (type == CFS_FT_SYMLINK) { buff_t value; buff_init(&value, lnk, strnlen(lnk, PATH_MAX)); /* Set symlink */ RC_WRAP_LABEL(rc, errfree, cfs_set_sysattr, &new_node, value, CFS_SYS_ATTR_SYMLINK); } /* Update the parent stat */ flags = STAT_CTIME_SET | STAT_MTIME_SET; if (type == CFS_FT_DIR) { /* Child dir has a "hardlink" to the parent ("..") */ flags |= STAT_INCR_LINK; } RC_WRAP_LABEL(rc, errfree, cfs_amend_stat, parent_stat, flags); RC_WRAP(kvs_end_transaction, kvstor, &index); errfree: kvnode_fini(&new_node); if (rc != 0) { kvs_discard_transaction(kvstor, &index); } out: if (fh != NULL) { cfs_fh_destroy(fh); } log_trace("parent_ino=%llu name=%s new_entry=%llu rc=%d", (unsigned long long int)parent_stat->st_ino, name, *new_entry, rc); return rc; } #define INODE_KFID_KEY_INIT INODE_ATTR_KEY_PTR_INIT int cfs_set_ino_oid(struct cfs_fs *cfs_fs, cfs_ino_t *ino, dstore_oid_t *oid) { int rc; cfs_inode_kfid_key_t *kfid_key = NULL; struct kvstore *kvstor = kvstore_get(); struct kvs_idx index; dassert(kvstor != NULL); index = cfs_fs->kvtree->index; RC_WRAP_LABEL(rc, out, kvs_alloc, kvstor, (void **)&kfid_key, sizeof(*kfid_key)); INODE_KFID_KEY_INIT(kfid_key, ino, CFS_KEY_TYPE_INODE_KFID); RC_WRAP_LABEL(rc, free_key, kvs_set, kvstor, &index, kfid_key, sizeof(cfs_inode_kfid_key_t), oid, sizeof(cfs_fid_t)); free_key: kvs_free(kvstor, kfid_key); out: log_trace("cfs_fs=%p ino=%llu oid=%" PRIx64 ":%" PRIx64 " rc=%d", cfs_fs, *ino, oid->f_hi, oid->f_lo, rc); return rc; } int cfs_ino_to_oid(struct cfs_fs *cfs_fs, const cfs_ino_t *ino, dstore_oid_t *oid) { int rc; cfs_inode_kfid_key_t *kfid_key = NULL; uint64_t kfid_size = 0; dstore_oid_t *oid_val = NULL; struct kvstore *kvstor = kvstore_get(); struct kvs_idx index; dassert(kvstor != NULL); index = cfs_fs->kvtree->index; dassert(ino != NULL); dassert(oid != NULL); RC_WRAP_LABEL(rc, out, kvs_alloc, kvstor, (void **)&kfid_key, sizeof(*kfid_key)); INODE_KFID_KEY_INIT(kfid_key, ino, CFS_KEY_TYPE_INODE_KFID); RC_WRAP_LABEL(rc, free_key, kvs_get, kvstor, &index, kfid_key, sizeof(cfs_inode_kfid_key_t), (void **)&oid_val, &kfid_size); *oid = *oid_val; kvs_free(kvstor, oid_val); free_key: kvs_free(kvstor, kfid_key); out: log_trace("cfs_fs=%p, *ino=%llu oid=%" PRIx64 ":%" PRIx64 " rc=%d, kfid_size=%" PRIu64 "", cfs_fs, *ino, oid->f_hi, oid->f_lo, rc, kfid_size); return rc; } int cfs_del_oid(struct cfs_fs *cfs_fs, const cfs_ino_t *ino) { int rc; cfs_inode_kfid_key_t *kfid_key = NULL; struct kvstore *kvstor = kvstore_get(); struct kvs_idx index; dassert(kvstor != NULL); index = cfs_fs->kvtree->index; dassert(ino != NULL); RC_WRAP_LABEL(rc, out, kvs_alloc, kvstor, (void **)&kfid_key, sizeof(*kfid_key)); INODE_KFID_KEY_INIT(kfid_key, ino, CFS_KEY_TYPE_INODE_KFID); RC_WRAP_LABEL(rc, free_key, kvs_del, kvstor, &index, kfid_key, sizeof(*kfid_key)); free_key: kvs_free(kvstor, kfid_key); out: log_trace("cfs_fs=%p, ino=%llu, rc=%d", cfs_fs, *ino, rc); return rc; }
19,258
C
.c
626
27.84984
91
0.664373
Seagate/cortx-fs
3
13
7
AGPL-3.0
9/7/2024, 2:18:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,882,692
cortxfs.c
Seagate_cortx-fs/src/cortxfs/cortxfs.c
/* * Filename: cortxfs.c * Description: CORTXFS file system interfaces * * Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * For any questions about this software or licensing, * please email [email protected] or [email protected]. */ #include <stdio.h> #include <errno.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <sys/time.h> #include <ini_config.h> #include <common/log.h> #include <common/helpers.h> #include <dstore.h> #include <dsal.h> /* dsal_init,fini */ #include <cortxfs.h> #include <internal/fs.h> #include <debug.h> #include <management.h> #include <nsal.h> /* nsal_init,fini */ static struct collection_item *cfg_items; static int cfs_initialized; int cfs_init(const char *config_path, const struct cfs_endpoint_ops *e_ops) { struct collection_item *errors = NULL; int rc = 0; struct collection_item *item = NULL; char *log_path = NULL; char *log_level = NULL; /** only initialize cortxfs once */ if (__sync_fetch_and_add(&cfs_initialized, 1)) { return 0; } rc = config_from_file("libcortxfs", config_path, &cfg_items, INI_STOP_ON_ERROR, &errors); if (rc) { free_ini_config_errors(errors); rc = -rc; goto out; } RC_WRAP(get_config_item, "log", "path", cfg_items, &item); /** Path not specified, use default */ if (item == NULL) { log_path = "/var/log/cortx/fs/cortxfs.log"; } else { log_path = get_string_config_value(item, NULL); } item = NULL; RC_WRAP(get_config_item, "log", "level", cfg_items, &item); if (item == NULL) { log_level = "LEVEL_INFO"; } else { log_level = get_string_config_value(item, NULL); } rc = log_init(log_path, log_level_no(log_level)); if (rc != 0) { rc = -EINVAL; goto out; } rc = utils_init(cfg_items); if (rc != 0) { log_err("utils_init failed, rc=%d", rc); goto log_cleanup; } rc = nsal_module_init(cfg_items); if (rc) { log_err("nsal_init failed, rc=%d", rc); goto utils_cleanup; } rc = dsal_init(cfg_items, 0); if (rc) { log_err("dsal_init failed, rc=%d", rc); goto nsal_cleanup; } rc = cfs_fs_init(e_ops); if (rc) { log_err("cfs_fs_init failed, rc=%d", rc); goto dsal_cleanup; } rc = management_init(); if (rc) { log_err("management_init failed, rc=%d", rc); goto cfs_fs_cleanup; } goto out; cfs_fs_cleanup: cfs_fs_fini(); dsal_cleanup: dsal_fini(); nsal_cleanup: nsal_module_fini(); utils_cleanup: utils_fini(); log_cleanup: log_fini(); out: if (rc) { free_ini_config_errors(errors); return rc; } /** @todo : remove all existing opened FD (crash recovery) */ return rc; } int cfs_fini(void) { int rc = 0; rc = management_fini(); if (rc) { log_err("management_fini failed, rc=%d", rc); } rc = cfs_fs_fini(); if (rc) { log_err("cfs_fs_fini failed, rc=%d", rc); } rc = nsal_module_fini(); if (rc) { log_err("nsal_fini failed, rc=%d", rc); } rc = dsal_fini(); if (rc) { log_err("dsal_fini failed, rc=%d", rc); } rc = utils_fini(); if (rc) { log_err("utils_fini failed, rc=%d", rc); } rc = log_fini(); if (rc) { log_err("log_fini failed, rc=%d ", rc); } free_ini_config_errors(cfg_items); return rc; }
4,094
C
.c
148
23.891892
75
0.637519
Seagate/cortx-fs
3
13
7
AGPL-3.0
9/7/2024, 2:18:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,882,707
cortxfs_xattr_ops.h
Seagate_cortx-fs/src/test/ut/cortxfs_xattr_ops.h
/* * Filename: cortxfs_xattr_ops.h * Description: Declaration of ops for xattr file and directory tests * * Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * For any questions about this software or licensing, * please email [email protected] or [email protected]. */ #include "ut_cortxfs_helper.h" #include <sys/xattr.h> /* XATTR_CREATE */ #define XATTR_NAME_SIZE_MAX 255 #define XATTR_VAL_SIZE_MAX 4096 #define XATTR_ENV_FROM_STATE(__state) (*((struct ut_xattr_env **)__state)) struct ut_xattr_env { struct ut_cfs_params ut_cfs_obj; char **xattr; }; /** * Test to set new (non-existing) xattr * Description: Set new (non-existing) xattr for file or directory * Strategy: * 1. Set xattr * 2. Verify setting xattr by getting xattr value * Expected behavior: * 1. No errors from CORTXFS API. * 2. xattr recieved from getxattr should match set xattr. */ void set_nonexist_xattr(void **state); /** * Setup for set existing xattr test * Description: Set new xattr for file or directory. * Strategy: * 1. Set xattr * Expected behavior: * 1. No errors from CORTXFS API. * 2. set xattr operation should be successful */ int set_exist_xattr_setup(void **state); /** * Test to set existing xattr * Description: Set existing xattr for file or directory. * Strategy: * 1. Set existing xattr * Expected behavior: * 1. No errors from CORTXFS API. * 2. setxattr operation should fail with error EEXIST */ void set_exist_xattr(void **state); /** * Test to replace new (non-existing) xattr * Description: Replace new (non-existing) xattr for file or directory. * Strategy: * 1. Set new (non-existing) xattr with flag XATTR_REPLACE * Expected behavior: * 1. No errors from CORTXFS API. * 2. Setxattr operation should fail with error ENOENT */ void replace_nonexist_xattr(void **state); /** * Setup for replace existing xattr test * Description: Set new xattr for file or directory. * Strategy: * 1. Set xattr * Expected behavior: * 1. No errors from CORTXFS API. * 2. setxattr operation should be successful */ int replace_exist_xattr_setup(void **state); /** * Test to replace existing xattr * Description: Replace existing xattr for file or directory. * Strategy: * 1. Replace existing xattr * 2. Verify replace xattr by getting xattr value * Expected behavior: * 1. No errors from CORTXFS API. * 2. setxattr operation with flag XATTR_REPLACE should be successful */ void replace_exist_xattr(void **state); /** * Setup for get existing xattr test * Description: Set xattr for file or directory. * Strategy: * 1. Set xattr * Expected behavior: * 1. No errors from CORTXFS API. * 2. Setxattr operation should be successful */ int get_exist_xattr_setup(void **state); /** * Test to get existing xattr * Description: Get existing xattr for file or directory. * Strategy: * 1. Get xattr value * 2. Verify output * Expected behavior: * 1. No errors from CORTXFS API. * 2. value from getxattr should match with set value. */ void get_exist_xattr(void **state); /** * Test to get nonexisting xattr * Description: Get nonexisting xattr for file or directory. * Strategy: * 1. Get xattr value * Expected behavior: * 1. No errors from CORTXFS API. * 2. getxattr soperation should fail with error ENOENT */ void get_nonexist_xattr(void **state); /** * Setup for remove existing xattr test * Description: Set xattr for file or directory. * Strategy: * 1. Set xattr * Expected behavior: * 1. No errors from CORTXFS API. * 2. Setxattr operation should be successful. */ int remove_exist_xattr_setup(void **state); /** * Test to remove existing xattr * Description: Remove existing xattr for file or directory. * Strategy: * 1. Remove xattr * 2. Verify xattr remove operation by getting xattr * Expected behavior: * 1. No errors from CORTXFS API. * 2. xattr remove operation should be successful * 3. getxattr should fail with error ENOENT. */ void remove_exist_xattr(void **state); /** * Test to remove nonexisting xattr * Description: Remove nonexisting xattr for file or directory. * Strategy: * 1. Remove xattr * Expected behavior: * 1. No errors from CORTXFS API. * 2. xattr remove operation should fail with error ENOENT */ void remove_nonexist_xattr(void **state); /** * Setup for list xattr test * Description: Set xattrs for file or directory. * Strategy: * 1. Create a file or directory. * 2. Set multiple xattr for file or directory. * Expected behavior: * 1. No errors from CORTXFS API. * 2. Setxattr operations should be successful. */ int listxattr_test_setup(void **state); /** * Test to list xattr * Description: List xattr for file or directory. * Strategy: * 1. List xattr * 2. xattrs values received from list xattr should match with set values * Expected behavior: * 1. No errors from CORTXFS API. * 2. list xattr operation should be successful * 3. xattr values set and recieved from list xattr should match. */ void listxattr_test(void **state); /** * Teardown for list xattr test * Description: Delete file or directory. * Strategy: * 1. Delete file or directory * Expected behavior: * 1. No errors from CORTXFS API. * 2. File deletion should be successful. */ int listxattr_test_teardown(void **state);
5,996
C
.h
185
30.513514
75
0.738477
Seagate/cortx-fs
3
13
7
AGPL-3.0
9/7/2024, 2:18:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,882,713
cortxfs_fh.h
Seagate_cortx-fs/src/include/cortxfs_fh.h
/* * Filename: cortxfs_fh.h * Description: CORTXFS File Handle API. * * Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * For any questions about this software or licensing, * please email [email protected] or [email protected]. */ /* Low-level Design * * CORTXFS File Handle Overview. * ----------------------------------- * * CORTXFS File Handle (cortxfs_fh) is an in-memory object that represents * a file object such as a regular file, a directory, a symlink etc. * * File Handles are obtained from the CORTXFS API using LOOKUP, READDIR or * deserialize calls. * These calls construct a new file handle per found object. READDIR produces * a file handle per each iteration over a directory. * File Handles cannot be constructed without making calls to the underlying * storage (to fetch kvnode). * * Root File Handle is a special file handle that can be constructed by * GETROOT call without specifying (parent_inode, dentry_name) pair. * However, it is still a subject to access checks. * * * FH Properties. * -------------- * A File Handle object has the following properties: * - Storage-level unique key (ObjectFID, IndexFID). * - FS-level unique inode number (uint64_t). * - per-object read-only attributes (type). * - per-object mutable attributes (mode_t, uid:gid, {a,c,m}time). * - Runtime locks. * - Access reference count. * - File state. * * * FH Serialization. * -------------- * * CORTXFS Users can serialize a FH into a buffer of a pre-defined size, store * it somewhere, and deseiralize later. Also, FH supports obtaining of a unique * in-memory key to be used in containers (maps, sets). * Methods: * - FH.serialize(buffer) - Writes on-wire representation into buffer. * - FH.key(buffer) - Writes unique in-memory key of the FH. * - deserialize(buffer, FH*) - Finds a file handle with the corresponding * on-wire data in the storage and creates a new FH. * * FH Memory management. * --------------------- * * Since FHs are opaque to the callers, they are contructed with malloc() calls. * However, it is not so efficient when a caller has its own File Handle * structure which agregates CORTXFS FH. To prevent multiple allocations of the * same entity, FH provides methods for placement initialization in pre-allocated * buffers. * Methods: * - create(args.., FH**) - Allocates memory and constructs a new FH. * - create_inplace(args.., buffer) - Constructs FH in a pre-allocated * memory region. * - destroy(FH*) - Destroys internal data and deallocates memory. * - destroy_inplace(FH*) - Destroys internal data. * - inplace(buffer) - Macro to convert a uint8_t* to FH*. * * Note: Inplace memory management is safe with enabled pointer aliasing * optimizations as long as the API does not allow callers to use the same * buffer in more than one argument: * @{code} * struct foo { * int bar; * int baz; * }; * char buffer[64]; * #define FOO(_buf) ((struct foo*) _buf) * * // Bad: * #define FOO_BAR(_buf) &((struct foo*) _buf)->bar * void fun1(struct foo *foo, int *bar) { * *bar = 20; * foo->bar = 10; * printf("%d, *bar); // Prints 20 instead of 10 * } * fun1(FOO(buffer), FOO_BAR(buffer)); * * // Better: * struct foo *foo = FOO(buffer); * fun1(foo, foo->bar); // Compiler can deduce bar's origin. * * // Ideal: * // Prevent the possiblity of aliasing * void fun1(struct foo *foo); * @{endcode} * * Inplace memorty menagement is not implemented yet and will a part of * futher optimizations when CORTXFS FH will be fully integrated in CORTXFS * namespace code. */ #ifndef CFS_FH_H_ #define CFS_FH_H_ #include "cortxfs.h" #include "nsal.h" struct cfs_fh; /* An invariant to check supplied fh is valid or not * @param[in] cred - User credentials. * @return true if fh is valid otherwise false */ inline bool cfs_fh_invariant(const struct cfs_fh *fh); /* The example of CORTXFS API described below allocates new file handles in * heap. Later we can change that to use in-place allocated structures to * avoid extra malloc/free calls. * The function looks up a directory entry `name` in the given `parent_fh` * directory using `cred` for checking access. * If name and inodes are matching with the parent fh then it will create the * new FH same as parent and return the reference of it. * It returns a new file handle object fh. * @param[in] cred - User credentials. * @param[in] parent_fh - Parent file handle. * @param[in] name - Dentry name. * @param[out] fh - Pointer to a new file handle object. * @return 0 or -errno. */ int cfs_fh_lookup(const cfs_cred_t *cred, struct cfs_fh *parent_fh, const char *name, struct cfs_fh **fh); /* Get a root file handle for given filesystem. * The function allocate, initialize it's all members and returns a new file * handle which represent the root directory of `fs` using `cred` for checking * access. * @param[in] fs - Filesystem context. * @param[in[ cred - User credentials. * @param[out] pfh - Pointer to the root FH object. */ int cfs_fh_getroot(struct cfs_fs *fs, const cfs_cred_t *cred, struct cfs_fh **pfh); /* Note: As of now, destroying FH does not update the stats in backend because * those are stale, the reason for that is FH is not supplied as input param to * each of the cortxfs API which can modify the stats of file directly in FH. * TODO: Temp_FH_op - to be removed * Uncomment the logic to dump the stats associated with FH once FH is present * everywhere all the update happens to FH * Dump the file attributes(kvnode) associated with a given FH * Release all resources and deallocate the memory region allocted for this FH * @param[in] fh - Any initialized FH. */ void cfs_fh_destroy(struct cfs_fh *fh); /* Note: This is a temporary API and shall be removed once FH is given as input * to all the operation in FS and all the updates(like stats of file) happens * to the FH * TODO: Temp_FH_op - to be removed * Dump the file attributes(kvnode) associated with a given FH * Release all resources and deallocate the memory region allocted for this FH * @param[in] fh - Any initialized FH. */ void cfs_fh_destroy_and_dump_stat(struct cfs_fh *fh); /* Get a pointer to node_id of a File Handle. * @param[in] fh - Any initialized FH. * @return Pointer to internal buffer which holds node_id number. */ node_id_t *cfs_node_id_from_fh(struct cfs_fh *fh); /* Get a pointer to inode numuber of a File Handle. * @param[in] fh - Any initialized FH. * @return Pointer to internal buffer which holds inode number. */ cfs_ino_t *cfs_fh_ino(struct cfs_fh *fh); /* Get a pointer to file system context from a File Handle. * @param[in] fh - Any initialized FH. * @return Pointer to FS context. */ struct cfs_fs *cfs_fs_from_fh(const struct cfs_fh *fh); /* Get a pointer to kvnode hold by a File Handle. * @param[in] fh - Any initialized FH. * @return Pointer to internal buffer which holds struct kvnode. */ struct kvnode *cfs_kvnode_from_fh(struct cfs_fh *fh); /* Get a pointer to attributes (stat) of a File Handle. * @param[in] fh - Any initialized FH. * @return Pointer to internal buffer which holds struct stat. */ struct stat *cfs_fh_stat(const struct cfs_fh *fh); /* The function allocates a new FH, intializes it's all the members and return * a newly allocated FH. * @param[in] fs - Filesystem context. * @param[in] ino_num - Inode number. * @param[out] pfh - Pointer the created FH object. * @return 0 or -errno. * @TODO: When file handle will be represented by unique 128bit FID, input to * this API will be that which will be used to load/form required paramete to * build FH */ int cfs_fh_from_ino(struct cfs_fs *fs, const cfs_ino_t *ino_num, struct cfs_fh **fh); /******************************************************************************/ /* Representation */ /** Writes FH id into a buffer. * @param[in] - FH to be serialized. * @param[in,out] - Buffer for the id. * The caller must ensure to allocate at least CFS_FH_ONWIRE_SIZE bytes, * or use cfs_fh_onwire_t structure as a storage. */ int cfs_fh_serialize(const struct cfs_fh *fh, void* buffer, size_t max_size); /** Creates a new in-memory file handle from a serialized file handle */ int cfs_fh_deserialize(struct cfs_fs *fs_ctx, const cfs_cred_t *cred, const void* buffer, size_t buffer_size, struct cfs_fh** pfh); /** Unique key for in-memory containers on the local machine side. * NOTE: It could be diffent from the on-wire handle. */ void cfs_fh_key(const struct cfs_fh *fh, void **pbuffer, size_t *psize); /** Max size of buffer to be used for FH serialization. * Note: the size is fixed however it is defined by the implementation * to prevent cases where CORTXFS FH on-wire has been extended or reduced * without recompiling the callers code. */ size_t cfs_fh_serialized_size(void); /* A temporary function to be used for serialization until cortxfs_fh_get_fsid * is implemented (or until CORTXFS start using FIDs as primary keys). * @param[in] fh - FH object. * @param[in] fsid - Unique FS number; allows to make FHs unique across multiple * filesystems. * @param[in,out] buffer - Buffer where serialized (on-wire) FH is stored. * @param[in] max_size - Size of the buffer. * @return -errno (fail) or positive number (succ) which corresponds to the * amount of bytes written into the buffer. */ int cfs_fh_ser_with_fsid(const struct cfs_fh *fh, uint64_t fsid, void *buffer, size_t max_size); /******************************************************************************/ #endif /* CFS_FH_H_ */
10,347
C
.h
242
40.475207
81
0.706763
Seagate/cortx-fs
3
13
7
AGPL-3.0
9/7/2024, 2:18:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,882,714
cortxfs.h
Seagate_cortx-fs/src/include/cortxfs.h
/* * Filename: cortxfs.h * Description: CORTXFS file system interfaces * * Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * For any questions about this software or licensing, * please email [email protected] or [email protected]. */ #ifndef _CFS_H #define _CFS_H #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <utils.h> #include <sys/stat.h> #include <str.h> /* str256_t */ #include <object.h> /* obj_id_t */ #include <md_common.h> /* MD_XATTR_SIZE_MAX */ #define CFS_XATTR_SIZE_MAX MD_XATTR_SIZE_MAX /* forword declations */ struct kvs_idx; struct cfs_fh; struct cfs_fs { struct namespace *ns; /* namespace object */ struct tenant *tenant; /* tenant object */ struct kvtree *kvtree; /* kvtree object */ struct kvnode *root_node; /* kvnode object for root node */ }; /** This structure is exposed to upper layer and have information regarding * the endpoint. this is filled during cfs_endpoint_scan*/ struct cfs_endpoint_info { str256_t *ep_name; /* endpoint name */ uint16_t ep_id; /* endpoint id(export_id) */ const char *ep_info; /* endpoint options */ }; /** This structure define endpoint operations for create/update the protocol * specific config file and will be initialized by protocol layer. */ struct cfs_endpoint_ops { /** constructor, will ganerate the protocol specific config file based * on endpoint stroed in kvs */ int (*init) (void); /* Basic destructor, clear the in momory structure created by constructor .*/ int (*fini) (void); /* will create export block in protocol specific config file */ int (*create) (const char *ep_name, uint16_t ep_id, const char *ep_info); /* will delete export block in protocol specific config file */ int (*delete) (uint16_t id); }; /** * Start the cortxfs library. This should be done by every thread using the library * * @note: this function will allocate required resources and set useful * variables to their initial value. As the programs ends cfs_init() should be * invoked to perform all needed cleanups. * * @param: const char *config. * @param: cosnt struct cfs_endpoint_ops *e_ops * @return 0 if successful, a negative "-errno" value in case of failure */ int cfs_init(const char *config, const struct cfs_endpoint_ops *e_ops); /** * Finalizes the cortxfs library. * This should be done by every thread using the library * * @note: this function frees what cfs_init() allocates. * * @param: none (void param) * @return 0 if successful, a negative "-errno" value in case of failure */ int cfs_fini(void); /** callback function, scans the tenant table. * the next iteration. * @param : cfs_scan_cb Function to be executed for each found endpoint. * @param : args call-back context * @return 0 if successful, a negative "-errno" value in case of failure. */ int cfs_endpoint_scan(int (*cfs_scan_cb)(const struct cfs_endpoint_info *info, void *args), void *args); /** * @todo : When cfs_ctx_t is defined, CFS_NULL_FS_CTX, * will also be redefined. */ #define CFS_NULL_FS_CTX (NULL) #define CFS_DEFAULT_CONFIG "/etc/cortx/cortxfs.conf" #define CFS_ROOT_INODE 2LL /* * We support block sizes from 2^12 (4K) t0 2^20 (1M). */ #define CFS_MIN_BLOCKSIZE 4096 #define CFS_DEFAULT_BLOCKSIZE CFS_MIN_BLOCKSIZE #define CFS_MAX_BLOCKSIZE 1048576 #define CFS_ROOT_UID 0 typedef unsigned long long int cfs_ino_t; #define STAT_MODE_SET 0x001 #define STAT_UID_SET 0x002 #define STAT_GID_SET 0x004 #define STAT_SIZE_SET 0x008 #define STAT_ATIME_SET 0x010 #define STAT_MTIME_SET 0x020 #define STAT_CTIME_SET 0x040 #define STAT_INCR_LINK 0x080 #define STAT_DECR_LINK 0x100 #define STAT_SIZE_ATTACH 0x200 #define STAT_OWNER_READ 0400 /* Read by owner. */ #define STAT_OWNER_WRITE 0200 /* Write by owner. */ #define STAT_OWNER_EXEC 0100 /* Execute by owner. */ #define STAT_GROUP_READ 0040 /* Read by group. */ #define STAT_GROUP_WRITE 0020 /* Write by group. */ #define STAT_GROUP_EXEC 0010 /* Execute by group. */ #define STAT_OTHER_READ 0004 /* Read by other. */ #define STAT_OTHER_WRITE 0002 /* Write by other. */ #define STAT_OTHER_EXEC 0001 /* Execute by other. */ #define CFS_ACCESS_READ 1 #define CFS_ACCESS_WRITE 2 #define CFS_ACCESS_EXEC 4 #define CFS_ACCESS_SETATTR 8 /** Access level required to create an object in a directory * (in other words, to link an inode into a directory). */ #define CFS_ACCESS_CREATE_ENTITY \ (CFS_ACCESS_WRITE | CFS_ACCESS_EXEC) /** Access level required to delete an object in a directory * (i.e., to unlink an inode from it). */ #define CFS_ACCESS_DELETE_ENTITY \ (CFS_ACCESS_WRITE | CFS_ACCESS_EXEC) /** Access level required to list objecs in a directory (READDIR). */ #define CFS_ACCESS_LIST_DIR \ (CFS_ACCESS_EXEC) typedef struct cfs_open_owner_ { int pid; int tid; } cfs_open_owner_t; typedef struct cfs_file_open_ { cfs_ino_t ino; cfs_open_owner_t owner; int flags; } cfs_file_open_t; enum cfs_file_type { CFS_FT_DIR = 1, CFS_FT_FILE = 2, CFS_FT_SYMLINK = 3 }; /* Number of groups supported by CORTXFS */ #define CORTXFS_CRED_GRPS 16 typedef struct cfs_cred__ { uid_t uid; gid_t gid; uint16_t total_grps; gid_t grp_list[CORTXFS_CRED_GRPS]; } cfs_cred_t; int cfs_access_check(const cfs_cred_t *cred, const struct stat *stat, int flags); typedef obj_id_t cfs_fid_t; typedef void *cfs_fs_ctx_t; /* @todo: * All below APIs need to be moved to internal headers * once all migration of cortxfs completes. */ /* cfs block size validator, returns 0 if valid */ static inline int cfs_is_bsize_valid(size_t fs_bsize) { int bsizes; for (bsizes = CFS_MIN_BLOCKSIZE; bsizes <= CFS_MAX_BLOCKSIZE; bsizes <<= 1) { if (bsizes == fs_bsize) { return 0; } } return -1; } /* Inode Attributes API */ int cfs_amend_stat(struct stat *stat, int flags); int cfs_create_entry(struct cfs_fh *parent_fh, cfs_cred_t *cred, char *name, char *lnk, mode_t mode, cfs_ino_t *new_entry, enum cfs_file_type type); /******************************************************************************/ /** */ /** * Change the name of a link between a parent node and a child node without * modifying the link itself. * @param parent_fh - Parent file handle * @param child_fh - Child file handle * @param old_name - Old file name * @param new_name - New file name to be replaced with for old file * * @return 0 if successful, a negative "-errno" value in case of failure */ int cfs_tree_rename_link(struct cfs_fh *parent_fh, struct cfs_fh *child_fh, const str256_t *old_name, const str256_t *new_name); /******************************************************************************/ /* CORTXFS internal data types */ /** Version of a cortxfs representation. */ typedef enum cfs_version { CFS_VERSION_0 = 0, CFS_VERSION_INVALID, } cfs_version_t; /** Key type associated with particular version of a namespace representation. */ typedef enum cfs_key_type { CFS_KEY_TYPE_DIRENT = 1, CFS_KEY_TYPE_PARENT, CFS_KEY_TYPE_STAT, CFS_KEY_TYPE_SYMLINK, CFS_KEY_TYPE_INODE_KFID, CFS_KEY_TYPE_GI_INDEX, CFS_KEY_TYPE_FS_ID_FID, CFS_KEY_TYPE_FS_NAME, CFS_KEY_TYPE_FS_ID, CFS_KEY_TYPE_FS_ID_NEXT, CFS_KEY_TYPE_INO_NUM_GEN, CFS_KEY_TYPE_INVALID, } cfs_key_type_t; typedef unsigned long int cfs_fsid_t; typedef struct cfs_inode_attr_key cfs_inode_kfid_key_t; struct cfs_fs_attr { cfs_fsid_t fs_id; cfs_fid_t fid; str256_t fs_name; }; /* Key metadata included into each key. * The metadata has the same size across all versions of CORTXFS object key representation * (2 bytes). */ struct cfs_key_md { uint8_t type; uint8_t version; } __attribute__((packed)); typedef struct cfs_key_md cfs_key_md_t; /* @todo remove this key structure when default fs is gone */ struct cfs_gi_index_key { cfs_key_md_t md; uint64_t fs_id; } __attribute((packed)); /* A generic key type for all attributes (properties) of an inode object */ struct cfs_inode_attr_key { cfs_fid_t fid; cfs_key_md_t md; } __attribute__((packed)); /* Max number of hardlinks for an object. */ #define CFS_MAX_LINK UINT32_MAX /* CORTXFS operations */ /** * Gets attributes for a known file handle. * * @note: the call is similar to stat() call in libc. It uses the structure * "struct stat" defined in the libC. * @param fh - File handle * @param stat - [OUT] points to inode's stat * * @return 0 if successful, a negative "-errno" value in case of failure */ int cfs_getattr(struct cfs_fh *cfs_fh, struct stat *stat); /** * Sets attributes for a known file handle. * * This call uses a struct stat structure as input. This structure will * contain the values to be set. More than one can be set in a single call. * The parameter "statflags: indicates which fields are to be considered: * STAT_MODE_SET: sets mode * STAT_UID_SET: sets owner * STAT_GID_SET: set group owner * STAT_SIZE_SET: set size (aka truncate but without unmapping) * STAT_ATIME_SET: sets atime * STAT_MTIME_SET: sets mtime * STAT_CTIME_SET: set ctime * * @param fh - File handle * @param cred - pointer to user's credentials * @param setstat - a stat structure containing the new values * @param statflags - a bitmap that tells which attributes are to be set * * @return 0 if successful, a negative "-errno" value in case of failure */ int cfs_setattr(struct cfs_fh *fh, cfs_cred_t *cred, struct stat *setstat, int statflag); /** * Check is a given user can access an inode. * * @note: this call is similar to POSIX's access() call. It behaves the same. * * @param ctx - File system context * @param cred - pointer to user's credentials * @param ino - pointer to inode whose access is to be checked. * @params flags - access to be tested. The flags are the same as those used * by libc's access() function. * * @return 0 if access is granted, a negative value means an error. -EPERM * is returned when access is not granted */ int cfs_access(struct cfs_fs *cfs_fs, const cfs_cred_t *cred, const cfs_ino_t *ino, int flags); /** A upper layer callback to be used in cfs_readddir_cb fucntion. * @param[in, out] ctx - Callback state * @param[in] name - Name of the dentry * @param[in] child_inode - inode number of a child * @retval true continue iteration. * @retval false stop iteration. */ typedef bool (*cfs_readdir_cb_t)(void *ctx, const char *name, cfs_ino_t child_ino); /* Walk over a directory "dir_ino" and call cb(cb_ctx, entry_name, node) which * will make a call to upper layer cb(cb_ctx, entry_name, child_stat) for * each dentry. * @param fs_ctx - File system context * @param cred - pointer to user's credentials * @param dir_no - pointer to directory inode * @param cb - Readdir callback to be called for each dir entry * @param cb_ctx - Callback context * @retval 0 on success, errno on error. */ int cfs_readdir(struct cfs_fs *cfs_fs, const cfs_cred_t *cred, const cfs_ino_t *dir_ino, cfs_readdir_cb_t cb, void *cb_ctx); /** * Creates a directory. * * @param ctx - pointer to filesystem context * @param cred - pointer to user's credentials * @param parent - pointer to parent directory's inode. * @param name - name of the directory to be created * @param mode - Unix mode for the new entry * @paran newdir - [OUT] if successfuly, will point to newly created inode * * @return 0 if successful, a negative "-errno" value in case of failure */ int cfs_mkdir(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *parent, char *name, mode_t mode, cfs_ino_t *newdir); /** * Finds the inode of an entry whose parent and name are known. This is the * basic "lookup" operation every filesystem implements. * * @param ctx - Filesystem context * @param cred - pointer to user's credentials * @param parent - pointer to parent directory's inode. * @param name - name of the entry to be found. * @paran myino - [OUT] points to the found ino if successful. * * @return 0 if successful, a negative "-errno" value in case of failure */ int cfs_lookup(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *parent, char *name, cfs_ino_t *ino); /** Hints for "cfs_rename" call. */ struct cfs_rename_flags { /** Destination file is open. Rename should not remove such an object * from the filesystems. The object will be unliked from the tree * instead of being destroyed. */ bool is_dst_open:1; }; #define CFS_RENAME_FLAGS_INIT { .is_dst_open = false, } /** * Renames an entry in a filesystem. * NOTE: The call has 3 optional paramters (psrc, pdst, flags) which * allows it to avoid redundant lookup() calls and could change its behavior. * * @param[in] fs_ctx - A context associated with the filesystem. * @param[in] cred - User's credentials. * @param[in] sino - Inode of the source dir. * @param[in] sname - Name of the entry within `sino`. * @param[in, opt] psrc - Inode of the source object. When NULL is specified, * the function does a lookup() call internally. * @param[in] dino - Inode of the destination dir. * @param[in] dname - Name of the entry within `dino`. * @param[in, opt] pdst - Inode of the destination object. When NULL is specified, * the function does a lookup() call internally. * @return 0 if successfull, otherwise -errno. */ int cfs_rename(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *sino_dir, char *sname, const cfs_ino_t *psrc, cfs_ino_t *dino_dir, char *dname, const cfs_ino_t *pdst, const struct cfs_rename_flags *pflags); /** * Removes a directory. It won't be deleted if not empty. * @param ctx - A context associated with a filesystem * @param cred - pointer to user's credentials * @param parent - pointer to parent directory's inode. * @param name - name of the directory to be remove. * * @return 0 if successful, a negative "-errno" value in case of failure */ int cfs_rmdir(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *parent, char *name); /** * Removes a file or a symbolic link. * Destroys the link between 'dir' and 'fino' and removes * the 'fino' object from the namespace if it has no links. * * @param[in] parent_fh - A parent file handle * @param[in] child_fh - A child file handle of an object to be removed. * @param[in] cred - User's credentials. * @param[in] name - Name of the entry to be removed. * @return 0 if successfull, otherwise -errno. * * @see ::cfs_destroy_orphaned_file and ::cfs_detach. */ int cfs_unlink2(struct cfs_fh *parent_fh, struct cfs_fh *child_fh, cfs_cred_t *cred, char *name); /** * Removes a file or a symbolic link. * Destroys the link between 'dir' and 'fino' and removes * the 'fino' object from the namespace if it has no links. * * @param[in] fs_ctx - A context associated with the filesystem. * @param[in] cred - User's credentials. * @param[in] dir - Inode of the parent directory. * @param[in, opt] fino - Inode of the object to be removed. If NULL is set * then cfs_unlink() will do an extra lookup() call. * @param[in] name - Name of the entry to be removed. * @return 0 if successfull, otherwise -errno. * * @see ::cfs_destroy_orphaned_file and ::cfs_detach. */ int cfs_unlink(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *dir, cfs_ino_t *fino, char *name); /** * Reads the content of a symbolic link * * @param fs_ctx - A context associated with the filesystem. * @param cred - pointer to user's credentials * @param link - pointer to the symlink's inode * @param content - [OUT] buffer containing the read content. * @param size[in, out] - Content size. The caller must put the size of 'content' * buffer. The function then fills in the actual size * of the symlink content. If the buffer is too small, * then the correponding error is returned. * @return 0 if successful, a negative "-errno" value in case of failure */ int cfs_readlink(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *link, char *content, size_t *size); /** * Creates a file. * * @param parent_fh - A pointer to valid parent file handle * @param cred - pointer to user's credentials * @param name - name of the file to be created * @param mode - Unix mode for the new entry * @paran newino - [OUT] if successfuly, will point to newly created inode * * @return 0 if successful, a negative "-errno" value in case of failure */ int cfs_creat(struct cfs_fh *parent_fh, cfs_cred_t *cred, char *name, mode_t mode, cfs_ino_t *newfile); /* Atomic file creation. * The functions create a new file, sets new attributes, gets them back * to the caller. That's all must be done within a transaction because we * cannot leave the file in the storage if we cannot set/get its stats. * TODO: This operations is not atomic yet but will be eventually. * @param[in] stat_in - New stats to be set. * @param[in] stat_in_flags - Defines which stat values must be set. * @param[out] stat_out - Final stat values of the created file. * @param[out] newfile - The inode number of the created file. */ int cfs_creat_ex(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *parent, char *name, mode_t mode, struct stat *stat_in, int stat_in_flags, cfs_ino_t *newfile, struct stat *stat_out); /** * Writes data to an opened fd * * @param ctx - filesystem context pointer * @param cred - pointer to user's credentials * @param fd - handle to opened file * @param buf - write data * @param count - size of buffer to be read * @param offset - write offset * * @return write size or a negative "-errno" in case of failure */ ssize_t cfs_write(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_file_open_t *fd, void *buf, size_t count, off_t offset); /** * Reads data from an opened fd * * @param ctx - filesystem context pointer * @param cred - pointer to user's credentials * @param fd - handle to opened file * @param buf - [OUT] read data * @param count - size of buffer to be read * @param offset - read offset * * @return read size or a negative "-errno" in case of failure */ ssize_t cfs_read(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_file_open_t *fd, void *buf, size_t count, off_t offset); /** Change size of a file. * Changes the size unmapping unused storage space in case of truncation. * The function is able to apply a set of new stat values along with * the new file size value. * @param ctx - Filesystem context. * @param ino - Inode of the file. * @param new_stat - A set of stat values to be set. * @param new_stat_flags - A set of flags which defines which stat values * have to be updated. STAT_SIZE_SET is a required flag. * @return 0 if successful, a negative "-errno" value in case of failure. */ int cfs_truncate(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *ino, struct stat *new_stat, int new_stat_flags); /** Removes a link between the parent inode and a filesystem object * linked into it with the dentry name. */ int cfs_detach(struct cfs_fs *cfs_fs, const cfs_cred_t *cred, const cfs_ino_t *parent, const cfs_ino_t *obj, const char *name); /** * Creates a symbolic link * * @param fs_ctx - A context associated with the filesystem. * @param cred - pointer to user's credentials * @param parent - pointer to parent directory's inode. * @param name - name of the directory to be created * @param content - the content of the symbolic link to be created * @paran newlnk - [OUT] if successfuly, will point to newly created inode * * @return 0 if successful, a negative "-errno" value in case of failure */ int cfs_symlink(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *parent, char *name, char *content, cfs_ino_t *newlnk); /** * Creates a file's hardlink * * @note: this call will failed if not performed on a file. * * @param fs_ctx - A context associated with the filesystem. * @param cred - pointer to user's credentials * @param ino - pointer to current inode. * @param dino - pointer to destination directory's inode * @param dname - name of the new entry in dino * * @return 0 if successful, a negative "-errno" value in case of failure */ int cfs_link(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *ino, cfs_ino_t *dino, char *dname); /** Destroys a file or a symlink object if it has no links in the file system. * NOTE: It does nothing if the object has one or more links. */ int cfs_destroy_orphaned_file(struct cfs_fs *cfs_fs, const cfs_ino_t *ino); /* Return the reference of the stat attribute for particular file held by given * kvnode, any update to this reference will always be visible inside kvnode * Caller has to make sure before finalization of given kvnode, updated stat has * been written to backend object store * @param[in] node * - Kvnode pointer which is already initialzed and having * stat attributes * * @return - A pointer to stat attribute, this API not suppose to fail */ struct stat *cfs_get_stat2(const struct kvnode *node); /* Store the stat associated with particular file inode held by given kvnode * * @param[in] node * - Kvnode pointer which is already initialized and hold * the stat attributes which needs to be stored * * @return - 0 on sucess on failure error code given by kvnode APIs */ int cfs_set_stat(struct kvnode *node); /* Xattr APIs */ /** * Sets an xattr to an inode entry * @note: xattr's name are zero-terminated strings. * * @param[in] fctx - File system ctx * @param[in] cred - pointer to user's credentials * @param[in] ino - entry's inode * @param[in] name - xattr's name * @param[in] value - buffer with xattr's value * @param[in] size - size of previous buffer * @param[in] flags - overwrite behavior, see "man 2 setxattr". Overwrite is * prohibited if set to XATTR_CREATE. The valid values of flags are * 0, XATTR_CREATE and XATTR_REPLACE * * @return 0 if successful, a negative "-errno" value in case of failure */ int cfs_setxattr(struct cfs_fs *cfs_fs, const cfs_cred_t *cred, const cfs_ino_t *ino, const char *name, char *value, size_t size, int flags); /** * Gets an xattr for an entry * @note: xattr's name is a zero-terminated string. * * @param[in] fctx - File system ctx * @param[in] cred - pointer to user's credentials * @param[in] ino - entry's inode * @param[in] name - xattr's name * @param[out] value - buffer in which xattr's value has been copied * @param[in,out] size - in: Size of passed value buffer.. * out: The size of the read xattr. * * @return size of xattr if successful,a negative "-errno" value in case of * failure */ size_t cfs_getxattr(struct cfs_fs *cfs_fs, cfs_cred_t *cred, const cfs_ino_t *ino, const char *name, char *value, size_t *size); /** * Fetches xattr names for a passed inode. * @note: xattr's name is a zero-terminated string. * * @param[in] fctx - File system ctx * @param[in] fid - 128 bit File (object) identifier. * @param[out] buf - The list which has the set of (null-terminated) * names, one after the other. * @param[out] count - Count of extended attribute names in the buf * @param[in] size -Size of buf. If the passed size is zero, the size is set to * current size of the the fetched attribute name list * [out] size - Size of the fetched attribute name list. * * @return zero for success, negative "-errno" value * in case of failure */ int cfs_listxattr(struct cfs_fs *cfs_fs, const cfs_cred_t *cred, const cfs_ino_t *ino, void *buf, size_t *count, size_t *size); /** * Removes an xattr * @note: xattr's name are zero-terminated strings. * * @param fs_ctx - filesystem context pointer * @param cred - pointer to user's credentials * @param ino - entry's inode * @param name - name of xattr to be removed * * @return 0 if successful, a negative "-errno" value in case of failure */ int cfs_removexattr(struct cfs_fs *cfs_fs, const cfs_cred_t *cred, const cfs_ino_t *ino, const char *name); /** * Removes all xattr for an inode * * @param fs_ctx - filesystem context pointer * @param cred - pointer to user's credentials * @param ino - entry's inode * * @return 0 if successful, a negative "-errno" value in case of failure */ int cfs_remove_all_xattr(struct cfs_fs *cfs_fs, cfs_cred_t *cred, cfs_ino_t *ino); #endif
25,351
C
.h
649
36.637904
90
0.696927
Seagate/cortx-fs
3
13
7
AGPL-3.0
9/7/2024, 2:18:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,882,716
error_handler.h
Seagate_cortx-fs/src/include/internal/error_handler.h
/* * Filename: error_handler.h * Description: Response error handling APIs * * Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * For any questions about this software or licensing, * please email [email protected] or [email protected]. */ #ifndef ERROR_HANDLER_H_ #define ERROR_HANDLER_H_ /* User defined error codes set greater than unix error codes.*/ enum error_code { INVALID_ETAG = 133, /* Invalid ETag */ BAD_DIGEST, /* Non-matching HASH */ MISSING_ETAG, /* Object ETag is missing */ INVALID_PAYLOAD, /* Payload data is invalid */ INVALID_PATH_PARAMS /* Invalid REST API path parameters */ }; /** * ############ Error response mapping structure ##################### */ /** * The error message ids for response messages. */ enum error_resp_id { /* Response IDs for fs create api */ ERR_RES_INVALID_FSNAME = 1, ERR_RES_FS_EXIST, /* Response IDs for fs delete api */ ERR_RES_FS_NONEXIST, ERR_RES_FS_EXPORT_EXIST, ERR_RES_FS_NOT_EMPTY, /* Generic IDs */ ERR_RES_INVALID_ETAG, ERR_RES_BAD_DIGEST, ERR_RES_MISSING_ETAG, ERR_RES_INVALID_PAYLOAD, ERR_RES_INVALID_PATH_PARAMS, /* Default error response ID */ ERR_RES_DEFAULT, ERR_RES_MAX }; /* * Mapping APIs corresponding to every REST API * * Returns an error response message based on the error code */ const char* fs_create_errno_to_respmsg(int err_code); const char* fs_delete_errno_to_respmsg(int err_code); #endif /* ERROR_HANDLER_H_ */
2,139
C
.h
60
33.716667
75
0.734171
Seagate/cortx-fs
3
13
7
AGPL-3.0
9/7/2024, 2:18:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,882,717
fs.h
Seagate_cortx-fs/src/include/internal/fs.h
/* * Filename: fs.h * Description: CORTXFS filesystemfunctions API. * * Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * For any questions about this software or licensing, * please email [email protected] or [email protected]. */ #ifndef _FS_H_ #define _FS_H_ #include <sys/queue.h> /* list */ #include <str.h> /* str256_t */ #include "cortxfs.h" /* cfs_tree_create_root */ #include "namespace.h" /* namespace methods */ /* Shared with uper layer, having fs and export informations */ struct cfs_fs_list_entry { str256_t *fs_name; const char *endpoint_info; }; /******************************************************************************/ /** Initialize cfs_fs: populate in memory list for available fs in kvs * * @param e_ops: const pointer to endpoint operations. * * @return 0 if successful, a negative "-errno" value in case of failure. */ int cfs_fs_init(const struct cfs_endpoint_ops *e_ops); /** finalize cfs_fs: free up the in memory list. * * @param void. * * @return 0 if successful, a negative "-errno" value in case of failure. */ int cfs_fs_fini(void); /** * Create FileSystem.. * * @fs_name - file system name structure. * * @fs_bsize - optional fs blocksize * * @return 0 if successful, a negative "-errno" value in case of failure */ int cfs_fs_create(const str256_t *fs_name, const size_t *fs_bsize); /** * Detele FileSystem.. * This will delete the in memmory object of link list. * @fs_name - file system name structure. * * @return 0 if successful, a negative "-errno" value in case of failure */ int cfs_fs_delete(const str256_t *fs_name); /** * lookup fs node in fs list. * * @param[in]: fs name. * @param[out]: fs node object. * * @return 0 if successful, a negative "-errno" value in case of failure. */ int cfs_fs_lookup(const str256_t *name, struct cfs_fs **fs); /** scans the namespace table. * Callback needs to copy the buffer containing ns, as it will be deleted in * the next iteration. * @param : fs_scan_cb fFunction to be executed for each found filesystem. * @param : args call-back context * @return 0 if successful, a negative "-errno" value in case of failure. */ int cfs_fs_scan_list(int (*fs_scan_cb)(const struct cfs_fs_list_entry *list, void *args), void *args); /** gets fs name. * * @param[in]: namespace object. * @param[out]: fs name. * * return void. */ void cfs_fs_get_name(const struct cfs_fs *fs, str256_t **name); /** * High level API: Open a fs context for the passed fs id. * @param fs_name[in]: filesystemname * @param index[out]: Initialized index for that fs_name. * * @return 0 if successful, a negative "-errno" value in case of failure */ int cfs_fs_open(const char *fs_name, struct cfs_fs **fs); /** * High level API: Close a fs context. * @param fs_ctx: fs_ctx to be finalized */ void cfs_fs_close(struct cfs_fs *cfs_fs); /* getter: get the filesystem id for given fs object. * * @param fs[in]: fs object. * @param ns_id[out]: filesystem id. * * return void. */ void cfs_fs_get_id(struct cfs_fs *fs, uint16_t *fs_id); /*****************************************************************************/ /* cortxfs fs_endpoint */ /** Initialize cfs_fs: populate in memory list for available endpoint in kvs * * @param void. * * @return 0 if successful, a negative "-errno" value in case of failure. */ int cfs_endpoint_init(void); /** finalize cfs_fs: set tenant to null in memory list. * * @param void. * * @return 0 if successful, a negative "-errno" value in case of failure. */ int cfs_endpoint_fini(void); /** * Create FileSystem. endpoint * * @param endpoint_name[in] - file system endpoint name. * @param endpoint_options[in] - file system endpoint name. * * @return 0 if successful, a negative "-errno" value in case of failure */ int cfs_endpoint_create(const str256_t *endpoint_name, const char *endpoint_options); /** * Detele FileSystem endpoint. * This will delete the in memmory object of link list. * * @param endpoint_name[in] - file system name structure. * * @return 0 if successful, a negative "-errno" value in case of failure */ int cfs_endpoint_delete(const str256_t *name); /** * getter function for endpoint information for given cfs_fs object. * * @param fs[in]: cfs_fs object. * @param info[out]: information associated with an endpoint object * * @ return void. */ void cfs_fs_get_endpoint(const struct cfs_fs *fs, void **info); /** * Initialize the sys attribute for root's id which will be used for * inode number generation (ref. CFS_SYS_ATTR_INO_NUM_GEN) * * @param cfs_fs - Valid file system context. * * @return 0 if successful, a negative "-errno" value in case of failure */ int cfs_ino_num_gen_init(struct cfs_fs *cfs_fs); /** * Deinit the sys attribute for root's id which was setup earlier via * cfs_setup_ino_num_gen() * * @param cfs_fs - Valid file system context. * * @return 0 if successful, a negative "-errno" value in case of failure */ int cfs_ino_num_gen_fini(struct cfs_fs *cfs_fs); #endif /* _FS_H_ */
5,754
C
.h
171
31.754386
85
0.693885
Seagate/cortx-fs
3
13
7
AGPL-3.0
9/7/2024, 2:18:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,882,721
cortxfs_internal.h
Seagate_cortx-fs/src/cortxfs/cortxfs_internal.h
/* * Filename: cortxfs_internal.h * Description: CORTXFS file system internal APIs * * Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * For any questions about this software or licensing, * please email [email protected] or [email protected]. */ #ifndef _CFS_INTERNAL_H #define _CFS_INTERNAL_H #include <dstore.h> #include <nsal.h> #include "cortxfs.h" #include "kvnode.h" enum cfs_sys_attr_type { CFS_SYS_ATTR_SYMLINK = 1, CFS_SYS_ATTR_INO_NUM_GEN, CFS_SYS_ATTR_MAX }; #define CFS_ROOT_INODE_NUM_GEN_START (CFS_ROOT_INODE + 1) /** * A kvnode is identified by a 128 bit node id. However, currently cortxfs uses * 64 bit inodes in it's apis to identify the entities. The following apis * are a temporary arrangement to convert 64 bit inodes to 128 bit node ids. * @TODO: Cleanup these apis when cortxfs filehandle (or equivalent) is * implemented. The filehandles would eventually use 128bit unique fids. */ static inline int node_id_to_ino(const node_id_t *nid, cfs_ino_t *ino) { dassert(nid != NULL); dassert(ino != NULL); *ino = nid->f_hi; return 0; } static inline int ino_to_node_id(const cfs_ino_t *ino, node_id_t *nid) { dassert(ino != NULL); dassert(nid != NULL); nid->f_hi = *ino; nid->f_lo = 0; return 0; } /** Set the extstore object identifier (kfid) with cortxfs inode as the key */ int cfs_set_ino_oid(struct cfs_fs *cfs_fs, cfs_ino_t *ino, dstore_oid_t *oid); /** Get the extstore object identifier for the passed cortxfs inode */ int cfs_ino_to_oid(struct cfs_fs *cfs_fs, const cfs_ino_t *ino, dstore_oid_t *oid); /** Delete the ino-kfid key-val pair from the kvs. Called during unlink/rm. */ int cfs_del_oid(struct cfs_fs *cfs_fs, const cfs_ino_t *ino); /* Initialize the kvnode with given parameters * * @param[in] node * - Kvnode pointer which will be initialized using kvnode * API to hold node information * @param[in] tree * - Kvtree pointer which will be stored in kvnode on init * @param[in] ino * - Inode of a file - file identifier * @param[in] bufstat * - Stat attribute buffer, stored in kvnode * * @return - 0 on sucess on failure error code given by kvnode APIs */ int cfs_kvnode_init(struct kvnode *node, struct kvtree *tree, const cfs_ino_t *ino, const struct stat *bufstat); /* Load kvnode for given file identifier from disk * * @param[in] node * - Kvnode pointer which will be initialized using kvnode * API to hold node information * @param[in] tree * - Kvtree pointer which will be stored in kvnode on init * @param[in] ino * - Inode of a file - file identifier * * @return - 0 on sucess on failure error code given by kvnode APIs */ int cfs_kvnode_load(struct kvnode *node, struct kvtree *tree, const cfs_ino_t *ino); /* Extract the stat attribute for particular file held by given kvnode * * @param[in] node * - Kvnode pointer which is already initialzed and having * stat attributes * @param[in] bufstat ** - Stat attribute buffer pointer to store stat attribute * * @return - 0 on sucess on failure error code given by kvnode APIs */ int cfs_get_stat(const struct kvnode *node, struct stat **bufstat); /* Delete the stat associated with particular file inode held by given kvnode * * @param[in] node * - Kvnode pointer which is initialized and needs to be * deleted * * @return - 0 on sucess on failure error code given by kvnode APIs */ int cfs_del_stat(struct kvnode *node); /* Update the stat hold by given kvnode for given flag and re-store it back to * the disk * * @param[in] node * - Kvnode pointer which is already initialzed and having * stat attributes * @param[in] flags - Flag mask for which stats needs to be updated * * @return - 0 on sucess on failure error code given by kvnode APIs */ int cfs_update_stat(struct kvnode *node, int flags); /* * This API will store any type of system attributes associated with * given node * * @param[in] node * - node for which system attributes to be stored * @param[in] value - Buffer which needs to be be stored * @param[in] attr_type - Type of system attirbutes to be stored * * @return - 0 on success else error code return by kvnode APIs */ int cfs_set_sysattr(const struct kvnode *node, const buff_t value, enum cfs_sys_attr_type attr_type); /* * This API will fetch any type of system attributes associated with * given node * * @param[in] node * - node for which system attributes to be fetched * @param[in] value * - Ponter to buffer to store attributes * @param[in] attr_type - Type of system attirbutes to be fetched * * @return - 0 on success else error code return by kvnode APIs */ int cfs_get_sysattr(const struct kvnode *node, buff_t *value, enum cfs_sys_attr_type attr_type); /* * This API will delete any type of system attributes associated with * given node * * @param[in] node * - node for which system attributes to be deleted * @param[in] attr_type - Type of system attirbutes to be deleted * * @return - 0 on success else error code return by kvnode APIs */ int cfs_del_sysattr(const struct kvnode *node, enum cfs_sys_attr_type attr_type); #endif
5,974
C
.h
145
39.131034
83
0.713769
Seagate/cortx-fs
3
13
7
AGPL-3.0
9/7/2024, 2:18:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,902,932
serveur.c
johnsamuelwrites_AlgoC/Groupe1/TP5/src/serveur.c
/* * SPDX-FileCopyrightText: 2021 John Samuel * * SPDX-License-Identifier: GPL-3.0-or-later * */ #include <arpa/inet.h> #include <errno.h> #include <netinet/in.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/epoll.h> #include <unistd.h> #include "serveur.h" int socketfd; // Déclaration globale de socketfd /** * Cette fonction envoie un message (*data) au client (client_socket_fd) * @param client_socket_fd : Le descripteur de socket du client. * @param sdata : Le message à envoyer. * @return EXIT_SUCCESS en cas de succès, EXIT_FAILURE en cas d'erreur. */ int renvoie_message(int client_socket_fd, char *data) { int data_size = write(client_socket_fd, (void *)data, strlen(data)); if (data_size < 0) { perror("Erreur d'écriture"); return EXIT_FAILURE; } return EXIT_SUCCESS; } /** * Cette fonction lit les données envoyées par le client, * et renvoie un message en réponse. * @param socketfd : Le descripteur de socket du serveur. * @param data : Le message. * @return EXIT_SUCCESS en cas de succès, EXIT_FAILURE en cas d'erreur. */ int recois_envoie_message(int client_socket_fd, char *data) { printf("Message reçu: %s\n", data); char code[10]; if (sscanf(data, "%9s:", code) == 1) // Assurez-vous que le format est correct { if (strcmp(code, "message:") == 0) { char message[1000]; printf("Votre message (max 1000 caractères): "); fgets(message, sizeof(message), stdin); return renvoie_message(client_socket_fd, message); } } return (EXIT_SUCCESS); } /** * Gestionnaire de signal pour Ctrl+C (SIGINT). * @param signal : Le signal capturé (doit être SIGINT pour Ctrl+C). */ void gestionnaire_ctrl_c(int signal) { printf("\nSignal Ctrl+C capturé. Sortie du programme.\n"); // Fermer le socket si ouvert if (socketfd != -1) { close(socketfd); } exit(0); // Quitter proprement le programme. } /** * Gère la communication avec un client spécifique. * * @param client_socket_fd Le descripteur de socket du client à gérer. */ void gerer_client(int client_socket_fd) { char data[1024]; while (1) { // Réinitialisation des données memset(data, 0, sizeof(data)); // Lecture des données envoyées par le client int data_size = read(client_socket_fd, data, sizeof(data)); if (data_size <= 0) { // Erreur de réception ou déconnexion du client if (data_size == 0) { // Le client a fermé la connexion proprement printf("Client déconnecté.\n"); } else { perror("Erreur de réception"); } // Fermer le socket du client et sortir de la boucle de communication close(client_socket_fd); break; // Sortir de la boucle de communication avec ce client } recois_envoie_message(client_socket_fd, data); } } /** * Configuration du serveur socket et attente de connexions. */ int main() { int bind_status; // Statut de la liaison struct sockaddr_in server_addr; // Structure pour l'adresse du serveur int option = 1; // Option pour setsockopt // Création d'une socket socketfd = socket(AF_INET, SOCK_STREAM, 0); // Vérification si la création de la socket a réussi if (socketfd < 0) { perror("Impossible d'ouvrir une socket"); return -1; } // Configuration de l'option SO_REUSEADDR pour permettre la réutilisation de l'adresse du serveur setsockopt(socketfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)); // Initialisation de la structure server_addr memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(PORT); // Port d'écoute du serveur server_addr.sin_addr.s_addr = INADDR_ANY; // Accepter les connexions de n'importe quelle adresse // Liaison de l'adresse à la socket bind_status = bind(socketfd, (struct sockaddr *)&server_addr, sizeof(server_addr)); // Vérification si la liaison a réussi if (bind_status < 0) { perror("bind"); return (EXIT_FAILURE); } // Enregistrement de la fonction de gestion du signal Ctrl+C signal(SIGINT, gestionnaire_ctrl_c); // Mise en attente de la socket pour accepter les connexions entrantes jusqu'à une limite de 10 connexions en attente listen(socketfd, 10); printf("Serveur en attente de connexions...\n"); struct sockaddr_in client_addr; // Structure pour l'adresse du client unsigned int client_addr_len = sizeof(client_addr); // Longueur de la structure client_addr int client_socket_fd; // Descripteur de socket du client // Boucle infinie while (1) { // Nouvelle connexion cliente client_socket_fd = accept(socketfd, (struct sockaddr *)&client_addr, &client_addr_len); if (client_socket_fd < 0) { perror("accept"); continue; // Continuer à attendre d'autres connexions en cas d'erreur } // Créer un processus enfant pour gérer la communication avec le client pid_t child_pid = fork(); if (child_pid == 0) { // Code du processus enfant close(socketfd); // Fermer la socket du serveur dans le processus enfant gerer_client(client_socket_fd); exit(0); // Quitter le processus enfant } else if (child_pid < 0) { perror("fork"); close(client_socket_fd); // Fermer le socket du client en cas d'erreur } else { // Code du processus parent close(client_socket_fd); // Fermer le socket du client dans le processus parent } } // Le programme ne devrait jamais atteindre cette ligne dans la boucle infinie return 0; }
5,790
C
.c
177
28.785311
119
0.680751
johnsamuelwrites/AlgoC
3
44
0
GPL-3.0
9/7/2024, 2:18:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,915,196
main.c
CazYokoyama_Open-Glider-Network-Groundstation/libraries/nmealib/examples/generator/main.c
/* * This file is part of nmealib. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <nmealib/generator.h> #include <nmealib/info.h> #include <nmealib/sentence.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main(int argc __attribute__((unused)), char *argv[] __attribute__((unused))) { NmeaMallocedBuffer buf; NmeaGenerator *gen; NmeaInfo info; size_t i; memset(&buf, 0, sizeof(buf)); nmeaInfoClear(&info); nmeaTimeSet(&info.utc, &info.present, NULL); nmeaInfoSetPresent(&info.present, NMEALIB_PRESENT_PDOP); nmeaInfoSetPresent(&info.present, NMEALIB_PRESENT_HDOP); nmeaInfoSetPresent(&info.present, NMEALIB_PRESENT_VDOP); nmeaInfoSetPresent(&info.present, NMEALIB_PRESENT_ELV); gen = nmeaGeneratorCreate(NMEALIB_GENERATOR_ROTATE, &info); if (!gen) { return -1; } for (i = 0; i < 10000; i++) { size_t gen_sz = nmeaGeneratorGenerateFrom(&buf, &info, gen, // NMEALIB_SENTENCE_GPGGA // | NMEALIB_SENTENCE_GPGSA // | NMEALIB_SENTENCE_GPGSV // | NMEALIB_SENTENCE_GPRMC // | NMEALIB_SENTENCE_GPVTG); if (gen_sz) { printf("%s\n", buf.buffer); usleep(500000); } } nmeaGeneratorDestroy(gen); free(buf.buffer); buf.buffer = NULL; buf.bufferSize = 0; return 0; }
1,938
C
.c
57
30.649123
82
0.709936
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,915,199
main.c
CazYokoyama_Open-Glider-Network-Groundstation/libraries/nmealib/examples/generate/main.c
/* * This file is part of nmealib. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <nmealib/info.h> #include <nmealib/nmath.h> #include <nmealib/sentence.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main(int argc __attribute__((unused)), char *argv[] __attribute__((unused))) { NmeaMallocedBuffer buf; NmeaInfo info; size_t i; memset(&buf, 0, sizeof(buf)); nmeaInfoClear(&info); nmeaTimeSet(&info.utc, &info.present, NULL); info.sig = NMEALIB_SIG_SENSITIVE; info.fix = NMEALIB_FIX_3D; info.latitude = 5000.0; info.longitude = 3600.0; info.speed = 2.14 * NMEALIB_MPS_TO_KPH; info.elevation = 10.86; info.track = 45; info.mtrack = 55; info.magvar = 55; info.hdop = 2.3; info.vdop = 1.2; info.pdop = 2.594224354; nmeaInfoSetPresent(&info.present, NMEALIB_PRESENT_SIG); nmeaInfoSetPresent(&info.present, NMEALIB_PRESENT_FIX); nmeaInfoSetPresent(&info.present, NMEALIB_PRESENT_LAT); nmeaInfoSetPresent(&info.present, NMEALIB_PRESENT_LON); nmeaInfoSetPresent(&info.present, NMEALIB_PRESENT_SPEED); nmeaInfoSetPresent(&info.present, NMEALIB_PRESENT_ELV); nmeaInfoSetPresent(&info.present, NMEALIB_PRESENT_TRACK); nmeaInfoSetPresent(&info.present, NMEALIB_PRESENT_MTRACK); nmeaInfoSetPresent(&info.present, NMEALIB_PRESENT_MAGVAR); nmeaInfoSetPresent(&info.present, NMEALIB_PRESENT_HDOP); nmeaInfoSetPresent(&info.present, NMEALIB_PRESENT_VDOP); nmeaInfoSetPresent(&info.present, NMEALIB_PRESENT_PDOP); info.satellites.inUseCount = NMEALIB_MAX_SATELLITES; nmeaInfoSetPresent(&info.present, NMEALIB_PRESENT_SATINUSECOUNT); for (i = 0; i < NMEALIB_MAX_SATELLITES; i++) { info.satellites.inUse[i] = (unsigned int) (i + 1); } nmeaInfoSetPresent(&info.present, NMEALIB_PRESENT_SATINUSE); info.satellites.inViewCount = NMEALIB_MAX_SATELLITES; for (i = 0; i < NMEALIB_MAX_SATELLITES; i++) { info.satellites.inView[i].prn = (unsigned int) i + 1; info.satellites.inView[i].elevation = (int) ((i * 10) % 90); info.satellites.inView[i].azimuth = (unsigned int) (i + 1); info.satellites.inView[i].snr = 99 - (unsigned int) i; } nmeaInfoSetPresent(&info.present, NMEALIB_PRESENT_SATINVIEWCOUNT | NMEALIB_PRESENT_SATINVIEW); for (i = 0; i < 10; i++) { size_t gen_sz = nmeaSentenceFromInfo(&buf, &info, // NMEALIB_SENTENCE_GPGGA // | NMEALIB_SENTENCE_GPGSA // | NMEALIB_SENTENCE_GPGSV // | NMEALIB_SENTENCE_GPRMC // | NMEALIB_SENTENCE_GPVTG); if (gen_sz) { printf("%s\n", buf.buffer); usleep(500000); info.speed += .1; } } free(buf.buffer); buf.buffer = NULL; buf.bufferSize = 0; return 0; }
3,330
C
.c
86
35.337209
96
0.71645
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,915,200
main.c
CazYokoyama_Open-Glider-Network-Groundstation/libraries/nmealib/examples/parse_file/main.c
/* * This file is part of nmealib. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <nmealib/context.h> #include <nmealib/info.h> #include <nmealib/nmath.h> #include <nmealib/parser.h> #include <libgen.h> #include <stdio.h> #include <string.h> #include <unistd.h> static const char * traceStr = "Trace: "; static const char * errorStr = "Error: "; static const char * eol = "\n"; static void trace(const char *str, size_t str_size) { write(1, traceStr, strlen(traceStr)); write(1, str, str_size); write(1, eol, strlen(eol)); } static void error(const char *str, size_t str_size) { write(1, errorStr, strlen(errorStr)); write(1, str, str_size); write(1, eol, strlen(eol)); } int main(int argc __attribute__((unused)), char *argv[] __attribute__((unused))) { char fn[2048]; const char * filename = &fn[0]; const char * deffile; const char * dn; NmeaInfo info; NmeaParser parser; FILE *file; char buff[2048]; size_t it = 0; NmeaPosition dpos; if (argc <= 1) { dn = dirname(argv[0]); deffile = "/../../samples/parse_file/gpslog.txt"; } else { dn = ""; deffile = argv[1]; } snprintf(&fn[0], sizeof(fn), "%s%s", dn, deffile); printf("Using file %s\n", filename); file = fopen(filename, "rb"); if (!file) { printf("Could not open file %s\n", filename); return -1; } nmeaContextSetTraceFunction(&trace); nmeaContextSetErrorFunction(&error); nmeaInfoClear(&info); nmeaParserInit(&parser, 0); while (!feof(file)) { size_t size = fread(&buff[0], 1, 100, file); nmeaParserParse(&parser, &buff[0], size, &info); nmeaMathInfoToPosition(&info, &dpos); printf("*** %03lu, Lat: %f, Lon: %f, Sig: %d, Fix: %d\n", (unsigned long) it++, dpos.lat, dpos.lon, info.sig, info.fix); } fseek(file, 0, SEEK_SET); /* } */ fclose(file); nmeaParserDestroy(&parser); return 0; }
2,518
C
.c
81
28.160494
113
0.677273
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,915,600
lmic_project_config.h
CazYokoyama_Open-Glider-Network-Groundstation/libraries/arduino-lmic/project_config/lmic_project_config.h
// project-specific definitions for otaa sensor // even if you have lora_project_config.h in your sketch directory. // some define are not used in all stack at compilation time, // even adding #include "lora_project_config.h" at top of the sketch // so put all in this file and it works all time //#define CFG_us915 1 #define CFG_eu868 1 #define CFG_sx1276_radio 1 // Use real interrupts //#define LMIC_USE_INTERRUPTS // Set SPI 8MHz //#define LMIC_SPI_FREQ 8000000 // Enable Debug (uncomment both lines) //#define LMIC_DEBUG_LEVEL 2 //#define LMIC_PRINTF_TO Serial // Use Original AES (More space but quicker) //#define USE_ORIGINAL_AES
648
C
.c
17
36.529412
68
0.765273
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,915,604
protocol.h
CazYokoyama_Open-Glider-Network-Groundstation/libraries/arduino-lmic/src/protocol.h
/* * Protocol.h * Copyright (C) 2017-2020 Linar Yusupov * * 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 PROTOCOL_H #define PROTOCOL_H enum { RF_PROTOCOL_LEGACY, /* Air V6 */ RF_PROTOCOL_OGNTP, /* Open Glider Network tracker */ RF_PROTOCOL_P3I, /* PilotAware */ RF_PROTOCOL_ADSB_1090, /* ADS-B 1090ES */ RF_PROTOCOL_ADSB_UAT, /* ADS-B UAT */ RF_PROTOCOL_FANET, /* Skytraxx */ /* Volunteer contributors are welcome */ RF_PROTOCOL_EID, /* UAS eID */ RF_PROTOCOL_GOTENNA /* goTenna Mesh */ }; enum { RF_MODULATION_TYPE_2FSK, RF_MODULATION_TYPE_LORA, RF_MODULATION_TYPE_PPM }; enum { RF_PREAMBLE_TYPE_55, RF_PREAMBLE_TYPE_AA }; enum { RF_CHECKSUM_TYPE_NONE, RF_CHECKSUM_TYPE_CCITT_FFFF, RF_CHECKSUM_TYPE_CCITT_0000, RF_CHECKSUM_TYPE_CCITT_1D02, RF_CHECKSUM_TYPE_GALLAGER, RF_CHECKSUM_TYPE_CRC8_107, RF_CHECKSUM_TYPE_RS }; enum { RF_BITRATE_100KBPS, RF_BITRATE_38400, RF_BITRATE_1042KBPS }; enum { RF_FREQUENCY_DEVIATION_19_2KHZ, RF_FREQUENCY_DEVIATION_25KHZ, RF_FREQUENCY_DEVIATION_50KHZ, RF_FREQUENCY_DEVIATION_625KHZ }; enum { RF_WHITENING_NONE, RF_WHITENING_MANCHESTER, RF_WHITENING_PN9, RF_WHITENING_NICERF }; enum { RF_PAYLOAD_DIRECT, RF_PAYLOAD_INVERTED }; enum { RF_RX_BANDWIDTH_SS_50KHZ, RF_RX_BANDWIDTH_SS_100KHZ, RF_RX_BANDWIDTH_SS_125KHZ, RF_RX_BANDWIDTH_SS_166KHZ, RF_RX_BANDWIDTH_SS_200KHZ, RF_RX_BANDWIDTH_SS_250KHZ, RF_RX_BANDWIDTH_SS_1567KHZ }; #define RF_MAX_SYNC_WORD_SIZE 8 typedef struct RF_PROTOCOL { const char name[10]; uint8_t type; uint8_t modulation_type; uint8_t preamble_type; uint8_t preamble_size; uint8_t syncword[RF_MAX_SYNC_WORD_SIZE]; uint8_t syncword_size; uint32_t net_id; uint8_t payload_type; uint8_t payload_size; uint8_t payload_offset; uint8_t crc_type; uint8_t crc_size; uint8_t bitrate; uint8_t deviation; uint8_t whitening; uint8_t bandwidth; uint16_t tx_interval_min; uint16_t tx_interval_max; } rf_proto_desc_t; #endif /* PROTOCOL_H */
2,828
C
.c
110
22.227273
73
0.688616
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,915,641
CC1310_LAUNCHXL.c
CazYokoyama_Open-Glider-Network-Groundstation/libraries/EasyLink/src/CC1310_LAUNCHXL.c
#ifdef ENERGIA_ARCH_CC13XX /* * Copyright (c) 2015-2016, Texas Instruments Incorporated * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of Texas Instruments Incorporated nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define DEVICE_FAMILY cc13x0 /* Include drivers */ #include <ti/drivers/rf/RF.h> /* RF hwi and swi priority */ const RFCC26XX_HWAttrs RFCC26XX_hwAttrs = { .hwiCpe0Priority = ~0, .hwiHwPriority = ~0, .swiCpe0Priority = 0, .swiHwPriority = 0, }; #endif // DEVICE_FAMILY == cc13x0
1,948
C
.c
43
43.186047
78
0.765633
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,915,783
protocol.h
CazYokoyama_Open-Glider-Network-Groundstation/libraries/arduino-basicmac/src/protocol.h
/* * Protocol.h * Copyright (C) 2017-2020 Linar Yusupov * * 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 PROTOCOL_H #define PROTOCOL_H enum { RF_PROTOCOL_LEGACY, /* Air V6 */ RF_PROTOCOL_OGNTP, /* Open Glider Network tracker */ RF_PROTOCOL_P3I, /* PilotAware */ RF_PROTOCOL_ADSB_1090, /* ADS-B 1090ES */ RF_PROTOCOL_ADSB_UAT, /* ADS-B UAT */ RF_PROTOCOL_FANET, /* Skytraxx */ /* Volunteer contributors are welcome */ RF_PROTOCOL_EID, /* UAS eID */ RF_PROTOCOL_GOTENNA /* goTenna Mesh */ }; enum { RF_MODULATION_TYPE_2FSK, RF_MODULATION_TYPE_LORA, RF_MODULATION_TYPE_PPM }; enum { RF_PREAMBLE_TYPE_55, RF_PREAMBLE_TYPE_AA }; enum { RF_CHECKSUM_TYPE_NONE, RF_CHECKSUM_TYPE_CCITT_FFFF, RF_CHECKSUM_TYPE_CCITT_0000, RF_CHECKSUM_TYPE_CCITT_1D02, RF_CHECKSUM_TYPE_GALLAGER, RF_CHECKSUM_TYPE_CRC8_107, RF_CHECKSUM_TYPE_RS }; enum { RF_BITRATE_100KBPS, RF_BITRATE_38400, RF_BITRATE_1042KBPS }; enum { RF_FREQUENCY_DEVIATION_19_2KHZ, RF_FREQUENCY_DEVIATION_25KHZ, RF_FREQUENCY_DEVIATION_50KHZ, RF_FREQUENCY_DEVIATION_625KHZ }; enum { RF_WHITENING_NONE, RF_WHITENING_MANCHESTER, RF_WHITENING_PN9, RF_WHITENING_NICERF }; enum { RF_PAYLOAD_DIRECT, RF_PAYLOAD_INVERTED }; enum { RF_RX_BANDWIDTH_SS_50KHZ, RF_RX_BANDWIDTH_SS_100KHZ, RF_RX_BANDWIDTH_SS_125KHZ, RF_RX_BANDWIDTH_SS_166KHZ, RF_RX_BANDWIDTH_SS_200KHZ, RF_RX_BANDWIDTH_SS_250KHZ, RF_RX_BANDWIDTH_SS_1567KHZ, RF_RX_BANDWIDTH_SS_62KHZ, RF_RX_BANDWIDTH_SS_83KHZ }; #define RF_MAX_SYNC_WORD_SIZE 8 typedef struct RF_PROTOCOL { const char name[10]; uint8_t type; uint8_t modulation_type; uint8_t preamble_type; uint8_t preamble_size; uint8_t syncword[RF_MAX_SYNC_WORD_SIZE]; uint8_t syncword_size; uint32_t net_id; uint8_t payload_type; uint8_t payload_size; uint8_t payload_offset; uint8_t crc_type; uint8_t crc_size; uint8_t bitrate; uint8_t deviation; uint8_t whitening; uint8_t bandwidth; uint16_t tx_interval_min; uint16_t tx_interval_max; } rf_proto_desc_t; #endif /* PROTOCOL_H */
2,884
C
.c
112
22.276786
73
0.689643
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,915,846
AircraftPosition.c
CazYokoyama_Open-Glider-Network-Groundstation/libraries/ASN1/AircraftPosition.c
/* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "AircraftModul" * found in "ogn.asn1" * `asn1c -fnative-types` */ #include "AircraftPosition.h" static asn_TYPE_member_t asn_MBR_AircraftPosition_1[] = { { ATF_NOFLAGS, 0, offsetof(struct AircraftPosition, callsign), (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)), 0, &asn_DEF_NativeInteger, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "callsign" }, { ATF_NOFLAGS, 0, offsetof(struct AircraftPosition, timestamp), (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)), 0, &asn_DEF_NativeInteger, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "timestamp" }, { ATF_NOFLAGS, 0, offsetof(struct AircraftPosition, lat), (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)), 0, &asn_DEF_NativeInteger, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "lat" }, { ATF_NOFLAGS, 0, offsetof(struct AircraftPosition, lon), (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)), 0, &asn_DEF_NativeInteger, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "lon" }, { ATF_NOFLAGS, 0, offsetof(struct AircraftPosition, alt), (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)), 0, &asn_DEF_NativeInteger, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "alt" }, { ATF_NOFLAGS, 0, offsetof(struct AircraftPosition, type), (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)), 0, &asn_DEF_NativeInteger, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "type" }, { ATF_NOFLAGS, 0, offsetof(struct AircraftPosition, stealth), (ASN_TAG_CLASS_UNIVERSAL | (1 << 2)), 0, &asn_DEF_BOOLEAN, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "stealth" }, { ATF_NOFLAGS, 0, offsetof(struct AircraftPosition, notrack), (ASN_TAG_CLASS_UNIVERSAL | (1 << 2)), 0, &asn_DEF_BOOLEAN, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "notrack" }, { ATF_NOFLAGS, 0, offsetof(struct AircraftPosition, course), (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)), 0, &asn_DEF_NativeInteger, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "course" }, { ATF_NOFLAGS, 0, offsetof(struct AircraftPosition, heading), (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)), 0, &asn_DEF_NativeInteger, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "heading" }, { ATF_NOFLAGS, 0, offsetof(struct AircraftPosition, spped), (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)), 0, &asn_DEF_NativeInteger, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "spped" }, }; static const ber_tlv_tag_t asn_DEF_AircraftPosition_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; static const asn_TYPE_tag2member_t asn_MAP_AircraftPosition_tag2el_1[] = { { (ASN_TAG_CLASS_UNIVERSAL | (1 << 2)), 6, 0, 1 }, /* stealth */ { (ASN_TAG_CLASS_UNIVERSAL | (1 << 2)), 7, -1, 0 }, /* notrack */ { (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)), 0, 0, 8 }, /* callsign */ { (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)), 1, -1, 7 }, /* timestamp */ { (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)), 2, -2, 6 }, /* lat */ { (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)), 3, -3, 5 }, /* lon */ { (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)), 4, -4, 4 }, /* alt */ { (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)), 5, -5, 3 }, /* type */ { (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)), 8, -6, 2 }, /* course */ { (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)), 9, -7, 1 }, /* heading */ { (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)), 10, -8, 0 } /* spped */ }; static asn_SEQUENCE_specifics_t asn_SPC_AircraftPosition_specs_1 = { sizeof(struct AircraftPosition), offsetof(struct AircraftPosition, _asn_ctx), asn_MAP_AircraftPosition_tag2el_1, 11, /* Count of tags in the map */ 0, 0, 0, /* Optional elements (not needed) */ -1, /* First extension addition */ }; asn_TYPE_descriptor_t asn_DEF_AircraftPosition = { "AircraftPosition", "AircraftPosition", &asn_OP_SEQUENCE, asn_DEF_AircraftPosition_tags_1, sizeof(asn_DEF_AircraftPosition_tags_1) /sizeof(asn_DEF_AircraftPosition_tags_1[0]), /* 1 */ asn_DEF_AircraftPosition_tags_1, /* Same as above */ sizeof(asn_DEF_AircraftPosition_tags_1) /sizeof(asn_DEF_AircraftPosition_tags_1[0]), /* 1 */ { 0, 0, SEQUENCE_constraint }, asn_MBR_AircraftPosition_1, 11, /* Elements count */ &asn_SPC_AircraftPosition_specs_1 /* Additional specs */ };
4,210
C
.c
147
25.863946
74
0.611576
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,916,084
Protocol_OGNTP.h
CazYokoyama_Open-Glider-Network-Groundstation/ognbase/Protocol_OGNTP.h
/* * * Protocol_OGNTP.h * Encoder and decoder for Open Glider Network tracker radio protocol * Copyright (C) 2017-2020 Linar Yusupov * * 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 PROTOCOL_OGNTP_H #define PROTOCOL_OGNTP_H #define OGNTP_PREAMBLE_TYPE RF_PREAMBLE_TYPE_AA #define OGNTP_PREAMBLE_SIZE 1 /* Warmup: 6 bits, preamble: 8 bits, value: 0xAA */ /* IEEE Manchester(0AF3656C) = AA 66 55 A5 96 99 96 5A */ #define OGNTP_SYNCWORD {0xAA, 0x66, 0x55, 0xA5, 0x96, 0x99, 0x96, 0x5A} #define OGNTP_SYNCWORD_SIZE 8 #define OGNTP_PAYLOAD_SIZE 20 #define OGNTP_CRC_TYPE RF_CHECKSUM_TYPE_GALLAGER #define OGNTP_CRC_SIZE 6 #define OGNTP_TX_INTERVAL_MIN 600 /* in ms */ #define OGNTP_TX_INTERVAL_MAX 1400 #include "ogn.h" typedef struct { /* Dummy type definition. Actual Tx/Rx packet format is defined in ogn.h */ } ogntp_packet_t; extern const rf_proto_desc_t ogntp_proto_desc; bool ogntp_decode(void *, ufo_t *, ufo_t *); size_t ogntp_encode(void *, ufo_t *); #endif /* PROTOCOL_OGNTP_H */
1,697
C
.c
40
39.425
85
0.718121
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,916,085
Traffic.h
CazYokoyama_Open-Glider-Network-Groundstation/ognbase/Traffic.h
/* * Traffic.h * Copyright (C) 2018-2020 Linar Yusupov * * 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 TRAFFICHELPER_H #define TRAFFICHELPER_H #include "SoC.h" #define ALARM_ZONE_NONE 100000 /* zone range is 1000m <-> 10000m */ #define ALARM_ZONE_LOW 1000 /* zone range is 700m <-> 1000m */ #define ALARM_ZONE_IMPORTANT 700 /* zone range is 400m <-> 700m */ #define ALARM_ZONE_URGENT 400 /* zone range is 0m <-> 400m */ #define VERTICAL_SEPARATION 300 /* metres */ #define VERTICAL_VISIBILITY_RANGE 500 /* value from FLARM data port specs */ #define TRAFFIC_VECTOR_UPDATE_INTERVAL 2 /* seconds */ #define TRAFFIC_UPDATE_INTERVAL_MS (TRAFFIC_VECTOR_UPDATE_INTERVAL * 1000) #define isTimeToUpdateTraffic() (millis() - UpdateTrafficTimeMarker > \ TRAFFIC_UPDATE_INTERVAL_MS) enum { TRAFFIC_ALARM_NONE, TRAFFIC_ALARM_DISTANCE, TRAFFIC_ALARM_VECTOR, TRAFFIC_ALARM_LEGACY }; void ParseData(void); void Traffic_setup(void); void Traffic_loop(void); void ClearExpired(void); void Traffic_Update(int); extern ufo_t fo, Container[MAX_TRACKING_OBJECTS], EmptyFO; #endif /* TRAFFICHELPER_H */
1,861
C
.c
44
38.227273
79
0.703518
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,916,087
hal_conf_extra.h
CazYokoyama_Open-Glider-Network-Groundstation/ognbase/hal_conf_extra.h
/* * hal_conf_extra.h * Copyright (C) 2019-2020 Linar Yusupov * * 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 HAL_CONF_EXTRA_H #define HAL_CONF_EXTRA_H /* * Override NUCLEO-L073RZ default Serial (2) assignment with S76G one's (1) */ #if defined(ARDUINO_NUCLEO_L073RZ) #if SERIAL_UART_INSTANCE == 2 #undef SERIAL_UART_INSTANCE #undef PIN_SERIAL_RX #undef PIN_SERIAL_TX #define SERIAL_UART_INSTANCE 1 #define PIN_SERIAL_RX PA10 #define PIN_SERIAL_TX PA9 // (Few) pre-production SoftRF Dongles had 1.5k D+ external pullup resistor // If you have one of these, then either: // - break down or un-solder the D+ pullup resistor, or // - keep using Arduino Core 1.8.0 for STM32, or // - uncomment #define USBD_FIXED_PULLUP line below then re-build and re-install SoftRF firmware, or // - unplug then plug in the Dongle again into a USB slot every time after you've done a settings change // // This indicates that there is an external and fixed 1.5k pullup // on the D+ line. This define is only needed on boards that have // internal pullups *and* an external pullup. Note that it would have // been better to omit the pullup and exclusively use the internal // pullups instead. //#define USBD_FIXED_PULLUP #endif /* SERIAL_UART_INSTANCE */ #endif /* ARDUINO_NUCLEO_L073RZ */ #if defined(ENERGIA_ARCH_CC13XX) /* * Built-in 128K flash memory of the CC1310F128 (7x7) * does fit for either: * - RECEIVER & BRIDGE modes, or * - NORMAL mode * but not both at the same time. */ #define ENABLE_NORMAL_MODE #define EXCLUDE_TEST_MODE #define EXCLUDE_SX12XX #define EXCLUDE_OGLEP3 #elif defined(ENERGIA_ARCH_CC13X2) #define USE_SERIAL_DEEP_SLEEP #define ENABLE_NORMAL_MODE #define EXCLUDE_TEST_MODE //#define EXCLUDE_SX12XX #endif /* ENERGIA_ARCH_CC13X0 & ENERGIA_ARCH_CC13X2 */ #endif /* HAL_CONF_EXTRA_H */
2,536
C
.c
64
36.78125
105
0.731368
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,916,089
Protocol_UAT978.h
CazYokoyama_Open-Glider-Network-Groundstation/ognbase/Protocol_UAT978.h
/* * * Protocol_UAT978.h * Decoder for UAT 978 MHz ADS-B radio protocol * Copyright (C) 2019-2020 Linar Yusupov * * 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 PROTOCOL_UAT978_H #define PROTOCOL_UAT978_H #include <uat.h> #include <uat_decode.h> #define UAT978_PREAMBLE_TYPE RF_PREAMBLE_TYPE_AA /* TBD */ #define UAT978_PREAMBLE_SIZE 4 /* TBD */ #define UAT978_SYNCWORD { 0xAC, 0xDD, 0xA4, 0xE2 } #define UAT978_SYNCWORD_SIZE 4 #define UAT978_PAYLOAD_SIZE LONG_FRAME_DATA_BYTES #define UAT978_CRC_TYPE RF_CHECKSUM_TYPE_RS #define UAT978_CRC_SIZE (LONG_FRAME_BYTES - LONG_FRAME_DATA_BYTES) #define UAT978_TX_INTERVAL_MIN 900 /* in ms */ /* TBD */ #define UAT978_TX_INTERVAL_MAX 1000 /* TBD */ #define STRATUX_UATRADIO_MAGIC_1 0x0a #define STRATUX_UATRADIO_MAGIC_2 0xb0 #define STRATUX_UATRADIO_MAGIC_3 0xcd #define STRATUX_UATRADIO_MAGIC_4 0xe0 typedef struct __attribute__ ((packed)) Stratux_LPUATRadio_UART_frame { byte magic1; byte magic2; byte magic3; byte magic4; uint16_t msgLen; int8_t rssi; uint32_t timestamp; uint8_t data[LONG_FRAME_BYTES]; } Stratux_frame_t; typedef struct { /* Dummy type definition. Actual Rx packet format is defined in uat_decode.h */ } uat978_packet_t; extern const rf_proto_desc_t uat978_proto_desc; bool uat978_decode(void *, ufo_t *, ufo_t *); size_t uat978_encode(void *, ufo_t *); #endif /* PROTOCOL_UAT978_H */
2,143
C
.c
55
35.436364
84
0.706025
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,916,096
Protocol_FANET.h
CazYokoyama_Open-Glider-Network-Groundstation/ognbase/Protocol_FANET.h
/* * * Protocol_FANET.h * * Encoder and decoder for open FANET radio protocol * URL: https://github.com/3s1d/fanet-stm32/tree/master/Src/fanet * * Copyright (C) 2017-2020 Linar Yusupov * * 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 PROTOCOL_FANET_H #define PROTOCOL_FANET_H /* * FANET uses LoRa modulation * FANET+ uses both LoRa (FANET) and FSK(FLARM) * * Freq: 868.2 [ 869.525 ] MHz * Modulation: LoRa (TM) * Parameters: BW_250 SF_7 CR_5 */ #define SOFRF_FANET_VENDOR_ID 0x07 //#define FANET_NEXT enum { FANET_AIRCRAFT_TYPE_OTHER, FANET_AIRCRAFT_TYPE_PARAGLIDER, FANET_AIRCRAFT_TYPE_HANGGLIDER, FANET_AIRCRAFT_TYPE_BALLOON, FANET_AIRCRAFT_TYPE_GLIDER, FANET_AIRCRAFT_TYPE_POWERED, FANET_AIRCRAFT_TYPE_HELICOPTER, FANET_AIRCRAFT_TYPE_UAV }; /* * Tracking frame type (#1), * Standard header, * No signature, * Broadcast */ typedef struct { unsigned int type : 6; unsigned int forward : 1; unsigned int ext_header : 1; unsigned int vendor : 8; unsigned int address : 16; #if defined(FANET_DEPRECATED) unsigned int latitude : 16; unsigned int longitude : 16; #else unsigned int latitude : 24; unsigned int longitude : 24; #endif /* units are degrees, seconds, and meter */ unsigned int altitude_lsb : 8; /* FANET+ reported alt. comes from ext. source */ unsigned int altitude_msb : 3; /* I assume that it is geo (GNSS) altitude */ unsigned int altitude_scale : 1; unsigned int aircraft_type : 3; unsigned int track_online : 1; unsigned int speed : 7; unsigned int speed_scale : 1; unsigned int climb : 7; unsigned int climb_scale : 1; unsigned int heading : 8; unsigned int turn_rate : 7; unsigned int turn_scale : 1; #if defined(FANET_NEXT) unsigned int qne_offset : 7; unsigned int qne_scale : 1; #endif } __attribute__((packed)) fanet_packet_t; typedef struct { /*HEADER*/ unsigned int type : 6; unsigned int forward : 1; unsigned int ext_header : 1; unsigned int vendor : 8; unsigned int address : 16; /*TYPE 4 Service*/ unsigned int header : 8; unsigned int latitude : 24; unsigned int longitude : 24; unsigned int temperature : 8; unsigned int wind_heading : 8; unsigned int s_scale : 1; unsigned int wind_speed : 7; unsigned int g_scale : 1; unsigned int wind_gusts : 7; unsigned int humidity : 8; unsigned int barometic_lsb : 8; unsigned int barometic_msb : 8; } __attribute__((packed)) fanet_packet_s; #define FANET_PAYLOAD_SIZE sizeof(fanet_packet_t) #define FANET_HEADER_SIZE 4 /* Declared air time of FANET+ is 20-40 ms */ #define FANET_TX_INTERVAL_MIN 2500 /* in ms */ #define FANET_TX_INTERVAL_MAX 3500 extern const rf_proto_desc_t fanet_proto_desc; bool fanet_decode(void *, ufo_t *, ufo_t *); size_t fanet_encode(void *, ufo_t *); size_t fanet_encode_sp(void *, ufo_t *); #endif /* PROTOCOL_FANET_H */
3,935
C
.c
115
29.721739
87
0.642175
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,916,114
Protocol_Legacy.h
CazYokoyama_Open-Glider-Network-Groundstation/ognbase/Protocol_Legacy.h
/* * Protocol_Legacy.h * Copyright (C) 2014-2015 Stanislaw Pusep * Copyright (C) 2019-2020 Linar Yusupov * * 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 PROTOCOL_LEGACY_H #define PROTOCOL_LEGACY_H /* IEEE Manchester(F531FAB6) = 55 99 A5 A9 55 66 65 96 */ #define LEGACY_PREAMBLE_TYPE RF_PREAMBLE_TYPE_55 #define LEGACY_PREAMBLE_SIZE 1 #define LEGACY_SYNCWORD {0x99, 0xA5, 0xA9, 0x55, 0x66, 0x65, 0x96} #define LEGACY_SYNCWORD_SIZE 7 #define LEGACY_PAYLOAD_SIZE 24 #define LEGACY_CRC_TYPE RF_CHECKSUM_TYPE_CCITT_FFFF #define LEGACY_CRC_SIZE 2 #define LEGACY_TX_INTERVAL_MIN 600 /* in ms */ #define LEGACY_TX_INTERVAL_MAX 1400 #define LEGACY_KEY1 { 0xe43276df, 0xdca83759, 0x9802b8ac, 0x4675a56b, \ 0xfc78ea65, 0x804b90ea, 0xb76542cd, 0x329dfa32 } #define LEGACY_KEY2 0x045d9f3b #define LEGACY_KEY3 0x87b562f4 /* FTD-12 Version: 7.00 */ enum { ADDR_TYPE_RANDOM, ADDR_TYPE_ICAO, ADDR_TYPE_FLARM, ADDR_TYPE_ANONYMOUS, /* FLARM stealth, OGN */ ADDR_TYPE_P3I, ADDR_TYPE_FANET }; enum { AIRCRAFT_TYPE_UNKNOWN, AIRCRAFT_TYPE_GLIDER, AIRCRAFT_TYPE_TOWPLANE, AIRCRAFT_TYPE_HELICOPTER, AIRCRAFT_TYPE_PARACHUTE, AIRCRAFT_TYPE_DROPPLANE, AIRCRAFT_TYPE_HANGGLIDER, AIRCRAFT_TYPE_PARAGLIDER, AIRCRAFT_TYPE_POWERED, AIRCRAFT_TYPE_JET, AIRCRAFT_TYPE_UFO, AIRCRAFT_TYPE_BALLOON, AIRCRAFT_TYPE_ZEPPELIN, AIRCRAFT_TYPE_UAV, AIRCRAFT_TYPE_RESERVED, AIRCRAFT_TYPE_STATIC }; enum { ALARM_LEVEL_NONE, ALARM_LEVEL_LOW, /* 13-18 seconds to impact */ ALARM_LEVEL_IMPORTANT, /* 9-12 seconds to impact */ ALARM_LEVEL_URGENT /* 0-8 seconds to impact */ }; enum { ALARM_TYPE_TRAFFIC, ALARM_TYPE_SILENT, ALARM_TYPE_AIRCRAFT, ALARM_TYPE_OBSTACLE }; enum { GNSS_STATUS_NONE, GNSS_STATUS_3D_GROUND, GNSS_STATUS_3D_MOVING }; enum { POWER_STATUS_BAD, POWER_STATUS_GOOD }; enum { TX_STATUS_OFF, TX_STATUS_ON }; typedef struct { /********************/ unsigned int addr : 24; unsigned int _unk0 : 4; unsigned int addr_type : 3; unsigned int _unk1 : 1; // unsigned int magic:8; /********************/ int vs : 10; unsigned int _unk2 : 2; unsigned int airborne : 1; unsigned int stealth : 1; unsigned int no_track : 1; unsigned int parity : 1; unsigned int gps : 12; unsigned int aircraft_type : 4; /********************/ unsigned int lat : 19; unsigned int alt : 13; /********************/ unsigned int lon : 20; unsigned int _unk3 : 10; unsigned int smult : 2; /********************/ int8_t ns[4]; int8_t ew[4]; /********************/ } legacy_packet_t; bool legacy_decode(void *, ufo_t *, ufo_t *); size_t legacy_encode(void *, ufo_t *); extern const rf_proto_desc_t legacy_proto_desc; #endif /* PROTOCOL_LEGACY_H */
3,530
C
.c
126
24.571429
73
0.667848
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,916,386
nmealib.h
CazYokoyama_Open-Glider-Network-Groundstation/libraries/nmealib/src/nmealib.h
/* * * NMEA library * URL: http://nmea.sourceforge.net * Author: Tim ([email protected]) * Licence: http://www.gnu.org/licenses/lgpl.html * $Id: nmea.h 17 2008-03-11 11:56:11Z xtimor $ * */ #ifndef __NMEALIB_H__ #define __NMEALIB_H__ #include "nmealib/util.h" #include "nmealib/validate.h" #include "nmealib/nmath.h" #include "nmealib/info.h" #include "nmealib/sentence.h" #include "nmealib/gpgga.h" #include "nmealib/gpgsa.h" #include "nmealib/gpgsv.h" #include "nmealib/gprmc.h" #include "nmealib/gpvtg.h" #include "nmealib/generator.h" #include "nmealib/parser.h" #include "nmealib/context.h" #endif /* __NMEALIB_H__ */
633
C
.h
25
23.88
49
0.722314
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,916,459
mavlink.h
CazYokoyama_Open-Glider-Network-Groundstation/libraries/mavlink/mavlink.h
#ifndef ARD_MAV_TO_FRSKY_MAVLINK_H_INCLUDED #define ARD_MAV_TO_FRSKY_MAVLINK_H_INCLUDED /* Copyright (c) 2012 - 2013 Andy Little ( Some parts of this work are based on: http://code.google.com/p/arducam-osd/source/browse/trunk/ArduCAM_OSD/MAVLink.ino Copyright (c) 2011. Sandro Benigno ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ #define MAVLINK_COMM_NUM_BUFFERS 1 #define MAVLINK_USE_CONVENIENCE_FUNCTIONS #define MAVLINK10 uint32_t get_num_heartbeats(); void read_mavlink(); void write_mavlink( uint32_t addr, float latitude, float longtitude, float altitude, float course, float h_speed, float v_speed, uint16_t squawk, char *callsign, uint8_t emitter_type); #include "include/mavlink/v1.0/mavlink_types.h" extern mavlink_system_t mavlink_system; #include "include/mavlink/v1.0/ardupilotmega/mavlink.h" #include "include/mavlink/v1.0/uAvionix/mavlink.h" #endif // ARD_MAV_TO_FRSKY_MAVLINK_H_INCLUDED
1,588
C
.h
33
43.545455
83
0.754742
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,917,024
hal.h
CazYokoyama_Open-Glider-Network-Groundstation/libraries/arduino-lmic/src/hal/hal.h
/******************************************************************************* * Copyright (c) 2015 Matthijs Kooijman * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * This the HAL to run LMIC on top of the Arduino environment. *******************************************************************************/ #ifndef _hal_hal_h_ #define _hal_hal_h_ #ifdef __cplusplus static const int NUM_DIO = 3; struct lmic_pinmap { u1_t nss; // Written HIGH in TX mode, LOW otherwise. // Typically used with a single RXTX switch pin. u1_t txe; // Written HIGH in RX mode, LOW otherwise. // Typicaly used with separate RX/TX pins, to allow switching off // the antenna switch completely. u1_t rxe; u1_t rst; u1_t dio[NUM_DIO]; u1_t busy; u1_t tcxo; }; // Use this for any unused pins. const u1_t LMIC_UNUSED_PIN = 0xff; #else /* __cplusplus */ #define NUM_DIO 3 #define LMIC_UNUSED_PIN 0xff typedef struct lmic_pinmap_struct { u1_t nss; // Written HIGH in TX mode, LOW otherwise. // Typically used with a single RXTX switch pin. u1_t txe; // Written HIGH in RX mode, LOW otherwise. // Typicaly used with separate RX/TX pins, to allow switching off // the antenna switch completely. u1_t rxe; u1_t rst; u1_t dio[NUM_DIO]; u1_t busy; u1_t tcxo; } lmic_pinmap; #endif /* __cplusplus */ // Declared here, to be defined an initialized by the application extern lmic_pinmap lmic_pins; #endif // _hal_hal_h_
1,711
C
.h
50
30.86
81
0.629022
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,917,034
si4032.h
CazYokoyama_Open-Glider-Network-Groundstation/libraries/OGN/rf/si4x32/si4032.h
#define REG_VERSION 0x01 #define REG_STATUS 0x02 // OUrrrrSS Overflow, Underflow, State: 00=Idle, 01=TX #define REG_OPMODE1 0x07 // RLWXTrPR Reset, LowBat, WakeUp, Xtal32kHz, Transmit, PLL. Ready #define REG_OPMODE2 0x08 // rrrrArrF AutoTx, FIFO reset #define REG_XTAL 0x09 // Xtal load capacitance #define REG_GPIO0 0x0B // #define REG_GPIO1 0x0C #define REG_GPIO2 0x0D #define REG_IOPORT 0x0E #define REG_ADCCONF 0x0F // ADC configuration: TSSSRRGG Trigger, Source, Ref, Gain #define REG_ADCOFS 0x10 #define REG_ADC 0x11 // ADC output value #define REG_TEMPCTRL 0x12 // temparature: RROTVVVV Range, Offset, Trim, Value #define REG_TEMPOFS 0x13 // temperature offset #define REG_LOWBAT 0x1A // [50mV, 5-bit] low-bat threshold, p.44 #define REG_BATVOLT 0x1B // [50mV, 5-bit] battery level = 1.7V + 50mV*ADC #define REG_DATACTRL 0x30 // #define REG_PKTSTAT 0x31 // xxxxxxTS, T=packet being transmitting, S=packet has been sent #define REG_HEADCTRL2 0x33 // #define REG_PREALEN 0x34 // preamble lenght in nibbles (half-bytes) #define REG_SYNC3 0x36 // #define REG_SYNC2 0x37 // #define REG_SYNC1 0x38 // #define REG_SYNC0 0x39 // #define REG_HEAD3 0x3A // #define REG_HEAD2 0x3B // #define REG_HEAD1 0x3C // #define REG_HEAD0 0x3D // #define REG_PKTLEN 0x3E // [bytes] packet length #define REG_TXPOWER 0x6D // [3dBm] transmitter power, 7=20dBm, p.32 #define REG_RATE1 0x6E // [1Msps/2^8 ] date rate MSB, p.26 #define REG_RATE0 0x6F // [1Msps/2^16] date rate LSB #define REG_MOD1 0x70 // modulation control #define REG_MOD2 0x71 #define REG_DEV 0x72 // [625Hz] frequency deviation #define REG_FREQOFS0 0x73 // #define REG_FREQOFS1 0x74 // #define REG_FREQ2 0x75 // [10MHz] band select, p.22 #define REG_FREQ1 0x76 // [10MHz/64000] carrier freq. MSB #define REG_FREQ0 0x77 // [10MHz/64000] carrier freq. LSB #define REG_HOPCHAN 0x79 // hopping channel select #define REG_HOPSTEP 0x7A // [10kHz] hopping step #define REG_FIFO 0x7F
3,365
C
.h
43
77
123
0.429046
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,917,051
smartrf_settings.h
CazYokoyama_Open-Glider-Network-Groundstation/libraries/EasyLink/src/smartrf_settings/smartrf_settings.h
#if defined(BOARD_CC1310_LAUNCHXL) #include "CC1310_LAUNCHXL/smartrf_settings.h" #elif defined(BOARD_CC1350_LAUNCHXL) #include "CC1350_LAUNCHXL/smartrf_settings.h" #elif defined(BOARD_CC1350STK) #include "CC1350STK/smartrf_settings.h" #endif
242
C
.h
7
33.571429
45
0.825532
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,917,052
smartrf_settings_predefined.h
CazYokoyama_Open-Glider-Network-Groundstation/libraries/EasyLink/src/smartrf_settings/smartrf_settings_predefined.h
#if defined(BOARD_CC1310_LAUNCHXL) #include "CC1310_LAUNCHXL/smartrf_settings_predefined.h" #elif defined(BOARD_CC1350_LAUNCHXL) #include "CC1350_LAUNCHXL/smartrf_settings_predefined.h" #elif defined(BOARD_CC1350STK) #include "CC1350STK/smartrf_settings_predefined.h" #endif
275
C
.h
7
38.285714
56
0.835821
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,917,277
nRF905_types.h
CazYokoyama_Open-Glider-Network-Groundstation/libraries/nRF905/nRF905_types.h
/* * Project: nRF905 AVR/Arduino Library/Driver * Author: Zak Kemble, [email protected] * Copyright: (C) 2013 by Zak Kemble * License: GNU GPL v3 (see License.txt) * Web: http://blog.zakkemble.co.uk/nrf905-avrarduino-librarydriver/ */ #ifndef NRF905_TYPES_H_ #define NRF905_TYPES_H_ #ifndef ARDUINO #include <stdbool.h> #if defined(RASPBERRY_PI) #include <raspi/raspi.h> #endif /* RASPBERRY_PI */ #endif #include "nRF905_config.h" /* typedef struct { uint8_t len; uint8_t dstAddress[NRF905_ADDR_SIZE]; uint8_t buffer[64]; } nrf905_packet_s; */ #endif /* NRF905_TYPES_H_ */
590
C
.h
24
23.125
68
0.737589
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,917,482
version.h
CazYokoyama_Open-Glider-Network-Groundstation/ognbase/version.h
//The version number conforms to semver.org format #define _VERSION_MAJOR 0 #define _VERSION_MINOR 1 #define _VERSION_PATCH 0 #define _VERSION_BUILD 28 #define _VERSION_DATE "06/02/2022" #define _VERSION_TIME "16:00:14" #define _VERSION_ONLY "0.1.0" #define _VERSION_NOBUILD "0.1.0 (06/02/2022)" #define _VERSION "0.1.0-28" //The version information is created automatically, more information here: https://github.com/rvdbreemen/autoinc-semver
444
C
.h
11
39.363636
119
0.771363
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,917,483
PVALID.h
CazYokoyama_Open-Glider-Network-Groundstation/ognbase/PVALID.h
/* * PVALID.h * Copyright (C) 2020 Manuel Rösel * * 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 <string.h> #include "SoC.h" #ifndef PVALIDHELPER_H #define PVALIDHELPER_H bool isPacketValid(uint32_t, double, double, double, time_t); static int distance(double, double, double, double); static double deg2rad(double); static double rad2deg(double); static void cleanUpPacket(uint8_t); static void shiftPackets(void); static bool appendPacket(uint32_t, double, double, time_t, uint8_t cnt); static int calcMaxDistance(double, time_t); typedef struct aircrafts { time_t timestamp; uint32_t addr; float latitude; float longitude; float altitude; float course; uint8_t pkt_counter; } aircrafts_t; #endif /* PVALIDHELPER_H */
1,371
C
.h
40
32
72
0.759819
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,917,484
WiFi.h
CazYokoyama_Open-Glider-Network-Groundstation/ognbase/WiFi.h
/* * WiFi.h * Copyright (C) 2019-2020 Linar Yusupov * * 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 WIFIHELPER_H #define WIFIHELPER_H #include "SoC.h" #if defined(ARDUINO) && !defined(EXCLUDE_WIFI) #include <WiFiUdp.h> #endif #define HOSTNAME "OGNB-" #define UDP_PACKET_BUFSIZE 256 enum { WIFI_TX_POWER_MIN = 0, /* 0 dBm */ WIFI_TX_POWER_MED = 10, /* 10 dBm */ WIFI_TX_POWER_MAX = 18 /* 18 dBm */ }; void WiFi_setup(void); void WiFi_loop(void); size_t Raw_Receive_UDP(uint8_t *); void Raw_Transmit_UDP(void); void WiFi_fini(void); bool Wifi_connected(); extern String host_name; #if defined(ARDUINO) && !defined(EXCLUDE_WIFI) extern WiFiUDP Uni_Udp; #endif extern char UDPpacketBuffer[UDP_PACKET_BUFSIZE]; #endif /* WIFIHELPER_H */
1,445
C
.h
43
30.302326
73
0.709607
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,917,486
RF.h
CazYokoyama_Open-Glider-Network-Groundstation/ognbase/RF.h
/* RF.h Copyright (C) 2019-2020 Linar Yusupov 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 RFHELPER_H #define RFHELPER_H #include <nRF905.h> #include <TimeLib.h> #include "SoC.h" #if defined(USE_BASICMAC) #include <basicmac.h> #else #include <lmic.h> #endif #include <hal/hal.h> #include <lib_crc.h> #include <protocol.h> #include <freqplan.h> #include "Protocol_Legacy.h" #include "Protocol_OGNTP.h" #include "Protocol_P3I.h" #include "Protocol_FANET.h" #include "Protocol_UAT978.h" #include "GNSS.h" #define maxof2(a, b) (a > b ? a : b) #define maxof3(a, b, c) maxof2(maxof2(a, b), c) #define maxof5(a, b, c, d, e) maxof2(maxof2(a, b), maxof3(c, d, e)) /* Max. paket's payload size for all supported RF protocols */ //#define MAX_PKT_SIZE 32 /* 48 = UAT LONG_FRAME_DATA_BYTES */ #define MAX_PKT_SIZE maxof5(LEGACY_PAYLOAD_SIZE, OGNTP_PAYLOAD_SIZE, \ P3I_PAYLOAD_SIZE, FANET_PAYLOAD_SIZE, \ UAT978_PAYLOAD_SIZE) #define RXADDR {0x31, 0xfa, 0xb6} // Address of this device (4 bytes) #define TXADDR {0x31, 0xfa, 0xb6} // Address of device to send to (4 bytes) enum { RF_IC_NONE, RF_IC_SX1276, RF_IC_SX1262 }; enum { RF_TX_POWER_FULL, RF_TX_POWER_LOW, RF_TX_POWER_OFF }; typedef struct rfchip_ops_struct { byte type; const char name[8]; bool (* probe)(); void (* setup)(); void (* channel)(uint8_t); bool (* receive)(); void (* transmit)(); void (* shutdown)(); } rfchip_ops_t; String Bin2Hex(byte *, size_t); uint8_t parity(uint32_t); byte RF_setup(void); void RF_SetChannel(void); void RF_SetHopChannel(void); void RF_loop(void); size_t RF_Encode(ufo_t *); size_t RF_Encode_Fanet_s(ufo_t *); bool RF_Transmit(size_t, bool); bool RF_Transmit_raw(size_t, bool); bool RF_Receive(void); void RF_Shutdown(void); uint8_t RF_Payload_Size(uint8_t); extern byte TxBuffer[MAX_PKT_SIZE], RxBuffer[MAX_PKT_SIZE]; extern unsigned long TxTimeMarker; extern const rfchip_ops_t* rf_chip; extern bool RF_SX12XX_RST_is_connected; extern size_t (* protocol_encode)(void *, ufo_t *); extern bool (* protocol_decode)(void *, ufo_t *, ufo_t *); extern int8_t RF_last_rssi; #endif /* RFHELPER_H */
2,870
C
.h
88
29.875
76
0.692839
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,917,488
OLED.h
CazYokoyama_Open-Glider-Network-Groundstation/ognbase/OLED.h
/* * OLEDHelper.h * Copyright (C) 2019-2021 Linar Yusupov * * 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 OLEDHELPER_H #define OLEDHELPER_H #include "SSD1306Wire.h" #define SSD1306_OLED_I2C_ADDR 0x3C byte OLED_setup(void); void OLED_write(char *, short, short, bool); void OLED_clear(void); void OLED_bar(uint8_t, uint8_t); void OLED_info(bool); void OLED_update(void); void OLED_disable(void); void OLED_enable(void); void OLED_draw_Bitmap(int16_t, int16_t, uint8_t, bool); #endif /* OLEDHELPER_H */
1,129
C
.h
31
34.548387
72
0.75713
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,917,490
EEPROM.h
CazYokoyama_Open-Glider-Network-Groundstation/ognbase/EEPROM.h
/* * EEPROM.h * Copyright (C) 2019-2020 Linar Yusupov * * 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 EEPROMHELPER_H #define EEPROMHELPER_H #include "SoC.h" #if !defined(EXCLUDE_EEPROM) #include <EEPROM.h> #endif /* EXCLUDE_EEPROM */ #define SOFTRF_EEPROM_MAGIC 0xBABADEDA #define SOFTRF_EEPROM_VERSION 0x0000005E typedef struct Settings { uint8_t mode; uint8_t aircraft_type; uint8_t txpower; uint8_t volume; uint8_t led_num; uint8_t pointer; bool nmea_g : 1; bool nmea_p : 1; bool nmea_l : 1; bool nmea_s : 1; bool resvd1 : 1; uint8_t nmea_out : 3; uint8_t bluetooth : 3; /* ESP32 built-in Bluetooth */ uint8_t alarm : 3; bool stealth : 1; bool no_track : 1; uint8_t gdl90 : 3; uint8_t d1090 : 3; uint8_t json : 2; uint8_t power_save; int8_t freq_corr; /* +/-, kHz */ } settings_t; typedef struct EEPROM_S { uint32_t magic; uint32_t version; settings_t settings; } eeprom_struct_t; typedef union EEPROM_U { eeprom_struct_t field; uint8_t raw[sizeof(eeprom_struct_t)]; } eeprom_t; void EEPROM_setup(void); void EEPROM_defaults(void); void EEPROM_store(void); extern settings_t* settings; #endif /* EEPROMHELPER_H */
1,854
C
.h
65
25.430769
72
0.70784
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,917,493
PNET.h
CazYokoyama_Open-Glider-Network-Groundstation/ognbase/PNET.h
/* * PNET.h * Copyright (C) 2020 Manuel Rösel * * 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 <string.h> #include "SoC.h" #ifndef PNETHELPER_H #define PNETHELPER_H void aes_init(); void PNETencrypt(unsigned char msg[],size_t msgLen, char **arr, size_t *arr_len); void PNETdecrypt(unsigned char msg[],size_t msgLen, char **arr, size_t *arr_len); #endif /* PNETHELPER_H */
995
C
.h
25
37.88
81
0.747664
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,917,495
Update.h
CazYokoyama_Open-Glider-Network-Groundstation/ognbase/Update.h
/* * OGN.h * Copyright (C) 2020 Manuel Rösel * * 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 <string.h> #include "SoC.h" #ifndef UPDATEHELPER_H #define UPDATEHELPER_H #endif /* UPDATEHELPER_H */
842
C
.h
22
35.181818
73
0.73399
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,917,503
MONIT.h
CazYokoyama_Open-Glider-Network-Groundstation/ognbase/MONIT.h
/* * OGN.h * Copyright (C) 2020 Manuel Rösel * * 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 <string.h> #include "SoC.h" #ifndef MONITHELPER_H #define MONITHELPER_H static bool MONIT_setup(); void MONIT_send_trap(); #endif /* MONITHELPER_H */
896
C
.h
24
34.166667
73
0.732558
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,917,504
Log.h
CazYokoyama_Open-Glider-Network-Groundstation/ognbase/Log.h
/* * Log.h * Copyright (C) 2019-2020 Linar Yusupov * * 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 LOGHELPER_H #define LOGHELPER_H #include "SoftRF.h" void Logger_send_udp(String *); void Logger_send_enc_udp(String *); #if LOGGER_IS_ENABLED #include <FS.h> extern File LogFile; void Logger_setup(void); void Logger_loop(void); void Logger_fini(void); #endif /* LOGGER_IS_ENABLED */ #endif /* LOGHELPER_H */
1,032
C
.h
30
32.533333
72
0.75504
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,917,507
Web.h
CazYokoyama_Open-Glider-Network-Groundstation/ognbase/Web.h
/* * Web.h * Copyright (C) 2020 Manuel Rösel * * 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 WEBHELPER_H #define WEBHELPER_H #include "SoC.h" #if defined(ARDUINO) && !defined(EXCLUDE_WIFI) #include <WiFiClient.h> #endif /* ARDUINO */ #include <TinyGPS++.h> #include "EEPROM.h" #include "RF.h" #define BOOL_STR(x) (x ? "true":"false") #define JS_MAX_CHUNK_SIZE 4096 void Web_setup(ufo_t* this_aircraft); void Web_loop(void); void Web_fini(void); void Web_start(void); void Web_stop(void); extern uint32_t tx_packets_counter, rx_packets_counter; //extern byte TxBuffer[PKT_SIZE]; extern String TxDataTemplate; #if defined(ARDUINO) && !defined(EXCLUDE_WIFI) extern WiFiClient client; #endif /* ARDUINO */ extern TinyGPSPlus gps; #endif /* WEBHELPER_H */
1,383
C
.h
41
31.95122
72
0.751885
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,917,508
RSM.h
CazYokoyama_Open-Glider-Network-Groundstation/ognbase/RSM.h
/* * RSM.h * Copyright (C) 2020 Manuel Rösel * * 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 <string.h> #include "SoC.h" #ifndef RSMHELPER_H #define RSMHELPER_H bool RSM_Setup(int); void RSM_receiver(); bool RSM_ExportAircraftPosition(); #endif /* RSMHELPER_H */
884
C
.h
25
33.56
72
0.755556
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,917,509
TTN.h
CazYokoyama_Open-Glider-Network-Groundstation/ognbase/TTN.h
/* * TTN.h * Copyright (C) 2018-2020 Linar Yusupov * * 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 TTNHELPER_H #define TTNHELPER_H #include "SoftRF.h" #if defined(ENABLE_TTN) void TTN_setup(void); void TTN_loop(void); #endif /* ENABLE_TTN */ #endif /* TTNHELPER_H */
919
C
.h
25
33.64
73
0.730159
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,917,510
SoC.h
CazYokoyama_Open-Glider-Network-Groundstation/ognbase/SoC.h
/* * SoC.h * Copyright (C) 2018-2020 Linar Yusupov * * 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 SOCHELPER_H #define SOCHELPER_H #define SOC_UNUSED_PIN 255 #include "SoftRF.h" #include "Platform_ESP32.h" typedef struct SoC_ops_struct { uint8_t id; const char name[16]; void (* setup)(); void (* loop)(); void (* fini)(); void (* reset)(); uint32_t (* getChipId)(); void * (*getResetInfoPtr)(); String (* getResetInfo)(); String (* getResetReason)(); uint32_t (* getFreeHeap)(); long (* random)(long, long); uint32_t (* maxSketchSpace)(); void (* WiFi_setOutputPower)(int); void (* WiFi_transmit_UDP)(const char* host, int, byte *, size_t); void (* WiFi_transmit_UDP_debug)(int, byte *, size_t); int (* WiFi_connect_TCP)(const char *, int); int (* WiFi_disconnect_TCP)(); int (* WiFi_transmit_TCP)(String); int (* WiFi_receive_TCP)(char *, int); int (* WiFi_isconnected_TCP)(); int (* WiFi_connect_TCP2)(const char *, int); int (* WiFi_disconnect_TCP2)(); int (* WiFi_transmit_TCP2)(String); int (* WiFi_receive_TCP2)(char *, int); int (* WiFi_isconnected_TCP2)(); void (* WiFiUDP_stopAll)(); bool (* WiFi_hostname)(String); int (* WiFi_clients_count)(); bool (* EEPROM_begin)(size_t); void (* SPI_begin)(); void (* swSer_begin)(unsigned long); void (* swSer_enableRx)(boolean); void (* Battery_setup)(); float (* Battery_voltage)(); void (* GNSS_PPS_handler)(); unsigned long (* get_PPS_TimeMarker)(); void (* UATSerial_begin)(unsigned long); void (* UATModule_restart)(); void (* WDT_setup)(); void (* WDT_fini)(); void (* Button_setup)(); void (* Button_loop)(); void (* Button_fini)(); } SoC_ops_t; enum { SOC_NONE, SOC_ESP8266, SOC_ESP32, SOC_RPi, SOC_CC13XX, SOC_STM32, SOC_PSOC4 }; extern const SoC_ops_t* SoC; #if defined(ESP8266) extern const SoC_ops_t ESP8266_ops; #endif #if defined(ESP32) extern const SoC_ops_t ESP32_ops; #endif #if defined(RASPBERRY_PI) extern const SoC_ops_t RPi_ops; #endif #if defined(ENERGIA_ARCH_CC13XX) || defined(ENERGIA_ARCH_CC13X2) extern const SoC_ops_t CC13XX_ops; #endif #if defined(ARDUINO_ARCH_STM32) extern const SoC_ops_t STM32_ops; #endif #if defined(__ASR6501__) extern const SoC_ops_t PSoC4_ops; #endif byte SoC_setup(void); void SoC_fini(void); #endif /* SOCHELPER_H */
3,054
C
.h
101
26.930693
72
0.667799
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,917,511
global.h
CazYokoyama_Open-Glider-Network-Groundstation/ognbase/global.h
extern String ogn_ssid[]; extern String ogn_wpass[]; extern int ssid_index; extern float ogn_lat; extern float ogn_lon; extern int ogn_alt; extern int16_t ogn_geoid_separation; extern uint8_t largest_range; extern String ogn_callsign; extern String ogn_server; extern uint16_t ogn_port; extern uint8_t ogn_band; extern uint8_t ogn_protocol_1; extern uint8_t ogn_protocol_2; extern bool ogn_debug; extern uint16_t ogn_debugport; extern bool ogn_itrackbit; extern bool ogn_istealthbit; extern bool ogn_sleepmode; extern uint16_t ogn_rxidle; extern uint16_t ogn_wakeuptimer; extern uint16_t ogn_range; extern bool fanet_enable; extern bool zabbix_enable; extern String zabbix_server; extern uint16_t zabbix_port; extern String zabbix_key; extern bool beers_show; extern bool remotelogs_enable; extern String remotelogs_server; extern uint16_t remotelogs_port; extern unsigned long oled_disable; extern bool testmode_enable; extern bool private_network; extern bool new_protocol_enable; extern String new_protocol_server; extern uint32_t new_protocol_port; extern bool ognrelay_enable; extern bool ognrelay_base;
1,175
C
.h
39
28.846154
36
0.791111
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,917,516
config.h
CazYokoyama_Open-Glider-Network-Groundstation/ognbase/config.h
/* * CONFIG.h * Copyright (C) 2020 Manuel Rösel * * 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 <string.h> #include "SoC.h" #ifndef CONFIGHELPER_H #define CONFIGHELPER_H bool OGN_save_config(void); bool OGN_read_config(void); #endif /* CONFIGHELPER_H */
907
C
.h
24
34.625
73
0.735936
CazYokoyama/Open-Glider-Network-Groundstation
3
12
0
GPL-3.0
9/7/2024, 2:18:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,967,271
string.c
petrvelicka_MandelbrotOS/src/string/string.c
#include <string.h> #include <stdint.h> #include <stddef.h> #include <stdbool.h> #include <kernel/alloc.h> #include <kernel/text.h> void *memset(void *b, int c, int len) { unsigned char *p = b; while (len > 0) { *p = c; p++; len--; } return (b); } void memcpy(void *dest, void *src, size_t n) { // Typecast src and dest addresses to (char *) char *csrc = (char *)src; char *cdest = (char *)dest; // Copy contents of src[] to dest[] for (int i = 0; i < (int)n; i++) cdest[i] = csrc[i]; } unsigned int strlen(const char *s) { unsigned int count = 0; while (*s != '\0') { count++; s++; } return count; } char *strcat(char *s1, const char *s2) { //Pointer should not null pointer if ((s1 == NULL) && (s2 == NULL)) return NULL; //Create copy of s1 char *start = s1; //Find the end of the destination string while (*start != '\0') { start++; } //Now append the source string characters //until not get null character of s2 while (*s2 != '\0') { *start++ = *s2++; } //Append null character in the last *start = '\0'; return s1; } char *strcpy(char *destination, const char *source) { if (destination == NULL) return NULL; char *ptr = destination; while (*source != '\0') { *destination = *source; destination++; source++; } *destination = '\0'; return ptr; } int atoi(char *str) { int res = 0; for (int i = 0; str[i] != '\0'; ++i) { res = res * 10 + str[i] - '0'; } return res; } char *itoa(int value, char *str, int base) { char *rc; char *ptr; char *low; // Check for supported base. if (base < 2 || base > 36) { *str = '\0'; return str; } rc = ptr = str; // Set '-' for negative decimals. if (value < 0 && base == 10) { *ptr++ = '-'; } // Remember where the numbers start. low = ptr; // The actual conversion. do { // Modulo is negative for negative value. This trick makes abs() unnecessary. *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz"[35 + value % base]; value /= base; } while (value); // Terminating the string. *ptr-- = '\0'; // Invert the numbers. while (low < ptr) { char tmp = *low; *low++ = *ptr; *ptr-- = tmp; } return rc; } char *dyncat(char *s1, char *s2) { char *toret, *mallocd; mallocd = (char *)malloc(1 + strlen(s1) + strlen(s2)); strcpy(mallocd, s1); strcat(mallocd, s2); toret = mallocd; free(mallocd); return toret; } int strcmp(char input[],char check[]) { int i,result=1; for(i=0; input[i]!='\0' || check[i]!='\0'; i++) { if(input[i] != check[i]) { result=0; break; } } return result; } int *create_delim_dict(char *delim) { int *d = (int *)malloc(sizeof(int) * DICT_LEN); memset((void *)d, 0, sizeof(int) * DICT_LEN); int i; for (i = 0; i < strlen(delim); i++) { d[delim[i]] = 1; } return d; } char *strtok(char *str, char *delim) { static char *last, *to_free; int *deli_dict = create_delim_dict(delim); if (!deli_dict) { return NULL; } if (str) { last = (char *)malloc(strlen(str) + 1); if (!last) { free(deli_dict); } to_free = last; strcpy(last, str); } while (deli_dict[*last] && *last != '\0') { last++; } str = last; if (*last == '\0') { free(deli_dict); free(to_free); return NULL; } while (*last != '\0' && !deli_dict[*last]) { last++; } *last = '\0'; last++; free(deli_dict); return str; } int wspaceamount(char *a) { int i = 0, count = 0; while (a[i] != '\0') { if (a[i] == ' ') { count++; } i++; } return count; } int isdigit(int c) { if (c >= '0' && c <= '9') return c; else return 0; } float atof(const char *s) { float rez = 0, fact = 1; if (*s == '-') { s++; fact = -1; } for (int point_seen = 0; *s; s++) { if (*s == '.') { point_seen = 1; continue; } int d = *s - '0'; if (d >= 0 && d <= 9) { if (point_seen) fact /= 10.0f; rez = rez * 10.0f + (float)d; } } return rez * fact; } int tolower(int ch) { if (ch >= 'A' && ch <= 'Z') return ('a' + ch - 'A'); else return ch; }
4,586
C
.c
240
14.616667
108
0.515426
petrvelicka/MandelbrotOS
3
20
0
MPL-2.0
9/7/2024, 2:19:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,967,272
macros.h
petrvelicka_MandelbrotOS/src/include/macros.h
#ifndef __MACROS_H__ #define __MACROS_H__ #define pass ;; static int disable_interrupts() { __asm__ __volatile__("cli"); return 0; } static int enable_interrupts() { __asm__ __volatile__("sti"); return 0; } #endif // !__MACROS_H__
246
C
.c
14
15.5
31
0.615721
petrvelicka/MandelbrotOS
3
20
0
MPL-2.0
9/7/2024, 2:19:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,967,274
alloc.h
petrvelicka_MandelbrotOS/src/include/kernel/alloc.h
#ifndef __SHMALL_H__ #define __SHMALL_H__ #include <stdint.h> #include <stddef.h> int init_heap(uint32_t start); void *malloc(uint32_t size); void free(void *ptr); void *calloc(size_t n, size_t size); void *realloc(void *ptr, size_t len); #endif // !__SHMALL_H__
265
C
.c
10
25.3
37
0.695652
petrvelicka/MandelbrotOS
3
20
0
MPL-2.0
9/7/2024, 2:19:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,967,275
hw.c
petrvelicka_MandelbrotOS/src/arch/i386/hw.c
#include <hw.h> // From Bran's OSDEV series because I can't be bothered to write my own. unsigned char inb(unsigned short _port) { unsigned char rv; __asm__ __volatile__("inb %1, %0" : "=a"(rv) : "dN"(_port)); return rv; } void outb(unsigned short _port, unsigned char _data) { __asm__ __volatile__("outb %1, %0" : : "dN"(_port), "a"(_data)); } uint16_t inw(uint16_t _port) { uint16_t rv; __asm__ volatile("inw %1, %0" : "=a"(rv) : "dN"(_port)); return rv; } void io_wait(void) { __asm__ volatile("jmp 1f\n\t" "1:jmp 2f\n\t" "2:"); }
738
C
.c
30
16.8
72
0.448864
petrvelicka/MandelbrotOS
3
20
0
MPL-2.0
9/7/2024, 2:19:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,967,278
cpuid.c
petrvelicka_MandelbrotOS/src/arch/i386/cpuid.c
#include <kernel/cpuid.h> #include <kernel/text.h> #include <cpuid.h> #include <stdint.h> #include <string.h> void cpuid(int code, uint32_t *a, uint32_t *d) { __asm__("cpuid" : "=a"(*a), "=d"(*d) : "a"(code) : "ecx", "ebx"); } int cpuid_string(int code, uint32_t where[4]) { __asm__("cpuid" : "=a"(*where), "=b"(*(where + 1)), "=c"(*(where + 2)), "=d"(*(where + 3)) : "a"(code)); return (int)where[0]; } int get_model(void) { int ebx, unused; __cpuid(0, unused, ebx, unused, unused); return ebx; } int get_vendor() { int cpustri = cpuid_string(0, (uint32_t)"edx"); //printf("%u", cpustri); return cpustri; }
722
C
.c
32
18
56
0.51895
petrvelicka/MandelbrotOS
3
20
0
MPL-2.0
9/7/2024, 2:19:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,967,279
power.c
petrvelicka_MandelbrotOS/src/arch/i386/power.c
#include <kernel/power.h> #include <stdint.h> #include <hw.h> void reboot() { uint8_t good = 0x02; while (good & 0x02) good = inb(0x64); outb(0x64, 0xFE); __asm__("hlt"); }
191
C
.c
11
14.727273
25
0.605556
petrvelicka/MandelbrotOS
3
20
0
MPL-2.0
9/7/2024, 2:19:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,967,280
vbe.c
petrvelicka_MandelbrotOS/src/arch/i386/vbe.c
#include <multiboot.h> #include <kernel/vbe.h> #include <kernel/text.h> #include <stdbool.h> #include <font.h> bool baddraw(int x, int y) { if ((uint32_t)x > fb_width || (uint32_t)y > fb_height) { return true; } else { return false; } } int init_vbe(multiboot_info_t *mbi) { fb_addr = (void *)(unsigned long)mbi->framebuffer_addr; fb_pitch = (uint32_t)mbi->framebuffer_pitch; fb_width = (uint32_t)mbi->framebuffer_width; fb_height = (uint32_t)mbi->framebuffer_height; fb_bpp = (uint8_t)mbi->framebuffer_bpp; return 0; } int drawrect(int startx, int starty, int stopx, int stopy, int color) { int x, y; if (baddraw(startx, starty) || baddraw(stopx, stopy)) { return 1; } for (x = startx; x < stopx; x++) { for (y = starty; y < stopy; y++) { putpixel(x, y, color); } } return 0; } int drawborder(int startx, int starty, int stopx, int stopy, int thickness, int color, int incolor) { int x, y; for (x = startx; x < stopx; x++) { for (y = starty; y < stopy; y++) { putpixel(x, y, color); } } for (x = startx + thickness; x < stopx - thickness; x++) { for (y = starty + thickness; y < stopy - thickness; y++) { putpixel(x, y, incolor); } } return 0; } int putpixel(int x, int y, int color) { if (baddraw(x, y)) { return 1; } if (fb_bpp == 8) { multiboot_uint8_t *pixel = fb_addr + fb_pitch * y + x; *pixel = color; } else if (fb_bpp == 15 || fb_bpp == 16) { multiboot_uint16_t *pixel = fb_addr + fb_pitch * y + 2 * x; *pixel = color; } else if (fb_bpp == 24) { multiboot_uint32_t *pixel = fb_addr + fb_pitch * y + 3 * x; *pixel = (color & 0xffffff) | (*pixel & 0xff000000); } else if (fb_bpp == 32) { multiboot_uint32_t *pixel = fb_addr + fb_pitch * y + 4 * x; *pixel = color; } return 0; } void mandelbrot(float left, float top, float xside, float yside, int color) { float xscale, yscale, zx, zy, cx, tempx, cy; int x, y, i, j; int maxx, maxy, count; cls(); // getting maximum value of x-axis of screen maxx = fb_width; // getting maximum value of y-axis of screen maxy = fb_height; // setting up the xscale and yscale xscale = xside / maxx; yscale = yside / maxy; // scanning every point in that rectangular area. // Each point represents a Complex number (x + yi). // Iterate that complex number for (y = 1; y <= maxy - 1; y++) { for (x = 1; x <= maxx - 1; x++) { // c_real cx = x * xscale + left; // c_imaginary cy = y * yscale + top; // z_real zx = 0; // z_imaginary zy = 0; count = 0; // Calculate whether c(c_real + c_imaginary) belongs // to the Mandelbrot set or not and draw a pixel // at coordinates (x, y) accordingly // If you reach the Maximum number of iterations // and If the distance from the origin is // greater than 2 exit the loop while ((zx * zx + zy * zy < 4) && (count < 30)) { // Calculate Mandelbrot function // z = z*z + c where z is a complex number // tempx = z_real*_real - z_imaginary*z_imaginary + c_real tempx = zx * zx - zy * zy + cx; // 2*z_real*z_imaginary + c_imaginary zy = 2 * zx * zy + cy; // Updating z_real = tempx zx = tempx; // Increment count count = count + 1; } // To display the created fractal putpixel(x, y, (count * 8) + color); } } }
3,763
C
.c
141
20.865248
99
0.546162
petrvelicka/MandelbrotOS
3
20
0
MPL-2.0
9/7/2024, 2:19:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,967,284
kbd.c
petrvelicka_MandelbrotOS/src/kernel/kbd.c
#include <kernel/alloc.h> #include <kernel/kbd.h> #include <kernel/text.h> #include <kernel/irq.h> #include <stdbool.h> #include <stdint.h> #include <stddef.h> #include <macros.h> #include <string.h> #include <hw.h> static uint32_t kb_mode = 0; static char kb_map[128] = { 0, 0x1b, /* esc */ '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', '\b', '\t', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\n', 0, /* left ctrl */ 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '\'', '`', 0, /* left shift */ '\\', 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', 0, /* right shift */ '*', 0, /* alt */ ' ', /* space*/ 0, /* capslock */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* f1 ... f10 */ 0, /* num lock*/ 0, /* scroll Lock */ 0, /* home key */ 0, /* up arrow */ 0, /* page up */ '-', 0, /* left arrow */ 0, 0, /* right arrow */ '+', 0, /* end key*/ 0, /* down arrow */ 0, /* page down */ 0, /* insert key */ 0, /* delete key */ 0, 0, 0, 0, /* f11 key */ 0, /* f12 key */ 0, /* all other keys are undefined */ }; static char kb_shift_map[128] = { 0, 0x1b, /* esc */ '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '\b', '\t', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}', '\n', 0, /* left control */ 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', '\"', '~', 0, /* left shift */ '|', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '<', '>', '?', 0, /* right shift */ '*', 0, /* alt */ ' ', /* space bar */ 0, /* caps lock */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* f1 ... f10 */ 0, /* num lock*/ 0, /* scroll lock */ 0, /* home key */ 0, /* up arrow */ 0, /* page up */ '-', 0, /* left arrow */ 0, 0, /* right arrow */ '+', 0, /* end key*/ 0, /* down arrow */ 0, /* page down */ 0, /* insert key */ 0, /* delete key */ 0, 0, 0, 0, /* f11 key */ 0, /* f12 key */ 0, /* all other keys are undefined */ }; static char shift(char sc) { char ch = sc & 0x7f; // clear highest bit /* the previous scancode is 0xe0*/ if (kb_mode & E0ESC) { switch (ch) { case 0x1D: return CTRL; case 0x38: return ALT; } } else { switch (ch) { case 0x2A: case 0x36: return SHIFT; case 0x1D: return CTRL; case 0x38: return ALT; } } return 0; } char mapndebounce(uint8_t scancode) { uint8_t sc, m; char ch; sc = scancode; /* is a escape char? */ if (KB_IS_ESCAPE(sc)) { kb_mode |= E0ESC; pass; } if ((m = shift(sc))) { if (KB_IS_RELEASE(sc)) { /* clear mode when release the key */ kb_mode &= ~m; } else { kb_mode |= m; } return 0; } /* check alt shift and ctrl */ if (kb_mode & SHIFT) { ch = kb_shift_map[sc & 0x7f]; } else { ch = kb_map[sc & 0x7f]; } /* on release */ if (KB_IS_RELEASE(sc)) { kb_mode &= ~E0ESC; return 0; } /* on press */ else if (ch != 0) { return ch; } } void handelescape(uint8_t scancode) { uint8_t sc, m; char ch; sc = scancode; if (KB_IS_ESCAPE(sc)) { kb_mode |= E0ESC; pass; } if ((m = shift(sc))) { if (KB_IS_RELEASE(sc)) { kb_mode &= ~m; } else { kb_mode |= m; } return; } /* check alt shift and ctrl */ if (kb_mode & SHIFT) { ch = kb_shift_map[sc & 0x7f]; } else { ch = kb_map[sc & 0x7f]; } if (kb_mode & CTRL) { if (ch == 'l'){ cls(); } } if (kb_mode & ALT) { /* nothing to do ? */ } } void kbdhandler(register_t *r) { currkey = inb(KB_DATA); handelescape(currkey); } char *gets() { char *mallocd, *base; uint8_t m; size_t size = 0, index = 0; int chars_typed = 0; mallocd = (char *)malloc(sizeof(char)); while (true) { cursor(); char ch = mapndebounce(currkey); if ((inb(KB_STAT) & KB_STAT_OBF) == 0) { continue; } if (ch == '\n') { printf(" "); printf("\r\n"); break; } else if (ch == '\b') { if (chars_typed != 0) { mallocd = (char *)realloc(mallocd, chars_typed * sizeof(char)); chars_typed -= 1; printf("\b"); mallocd[chars_typed] = ' '; } } else if (ch != '\0') { printf("%c", ch); if (chars_typed != 0) { mallocd = (char *)realloc(mallocd, chars_typed * sizeof(char)); } mallocd[chars_typed] = ch; chars_typed++; } } mallocd[chars_typed + 1] = '\0'; base = mallocd; free(mallocd); return base; } int kbd_init() { irq_install_handler(1, kbdhandler); return 0; }
5,549
C
.c
258
16.147287
75
0.386735
petrvelicka/MandelbrotOS
3
20
0
MPL-2.0
9/7/2024, 2:19:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,967,286
init.c
petrvelicka_MandelbrotOS/src/kernel/init.c
#include <kernel/init.h> #include <kernel/text.h> #include <kernel/vbe.h> #include <kernel/kpanic.h> #include <stdbool.h> #include <string.h> #include <macros.h> #include <font.h> void init_check(int func, char *name, bool ness) { printf("Initing %s", name); if (func == 0) { //x = fb_width - 54; x = fb_width - ((GLYPH_WIDTH+1)*6) - 2; printf("[ "); fg_color = GREEN; printf("OK"); fg_color = FG; printf(" ]"); inited_funcs[inited_funs_no] = name; inited_funs_no++; } else { x = fb_width - ((GLYPH_WIDTH+1)*10) - 2; printf("[ "); fg_color = RED; printf("FAILED"); fg_color = FG; printf(" ]"); if (ness){ char* failure_point; //sprintf(failure_point, "%s%s", "Failed init Function - ", name); strcpy(failure_point, "Failed init function - "); strcat(failure_point, name); kpanic(failure_point, 19); } else{ pass; } } }
1,010
C
.c
43
18.046512
75
0.53886
petrvelicka/MandelbrotOS
3
20
0
MPL-2.0
9/7/2024, 2:19:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,967,290
alloc.c
petrvelicka_MandelbrotOS/src/kernel/alloc.c
#include <kernel/alloc.h> #include <string.h> #define HEAP_SIZE 0x10000 #define HEAP_MAGIC 0x42 #define ALIGN_TYPE char #define ALIGNMENT 16ul #define ALIGN_INFO sizeof(ALIGN_TYPE) * 16 static uint32_t *heap; static uint32_t index; #define ALIGN(ptr) \ if (ALIGNMENT > 1) \ { \ uint32_t diff; \ ptr = (void *)((uint32_t)ptr + ALIGN_INFO); \ diff = (uint32_t)ptr & (ALIGNMENT - 1); \ if (diff != 0) \ { \ diff = ALIGNMENT - diff; \ ptr = (void *)((uint32_t)ptr + diff); \ } \ *((ALIGN_TYPE *)((uint32_t)ptr - ALIGN_INFO)) = diff + ALIGN_INFO; \ } #define UNALIGN(ptr) \ if (ALIGNMENT > 1) \ { \ uint32_t diff = *((ALIGN_TYPE *)((uint32_t)ptr - ALIGN_INFO)); \ if (diff < (ALIGNMENT + ALIGN_INFO)) \ { \ ptr = (void *)((uint32_t)ptr - diff); \ } \ } int init_heap(uint32_t start) { heap = (uint32_t *)start; for (int i = 0; i < HEAP_SIZE; i++) heap[i] = 0; heap[0] = HEAP_MAGIC; index = 1; return 0; } int count() { int i = 0; uint32_t *iterator = heap + 1; do { iterator += iterator[0] + 1; i++; } while (iterator[0] != 0); return i; } void *malloc(uint32_t size) { if (size < 1) return NULL; size = size + ALIGNMENT + ALIGN_INFO; heap[index] = size; index += size + 1; void *p = (void *)(heap + index - size); ALIGN(p); return p; } void free(void *ptr) { (void)ptr; UNALIGN(ptr); } void *realloc(void *ptr, size_t len) { void *real; real = malloc(len); memset(real, 0, len); if (real) memcpy(real, ptr, len); free(ptr); return (real); } void *calloc(size_t n, size_t size) { size_t total = n * size; void *p = malloc(total); if (!p) return NULL; return memset(p, 0, total); }
2,692
C
.c
85
27.588235
74
0.374903
petrvelicka/MandelbrotOS
3
20
0
MPL-2.0
9/7/2024, 2:19:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,967,304
kernelinf.h
petrvelicka_MandelbrotOS/src/include/kernelinf.h
#ifndef __KERNELINF_H__ #define __KENRELINF_H__ #define KERNEL_NAME "mandelbrotOS" #define KERNEL_VERS "0.0.1" #define KENREL_DATE __DATE__ #define KERNEL_TIME __TIME__ #define KERNEL_ARTS " _____ _ _ _ _ _____ _____ \r\n \ | |___ ___ _| |___| | |_ ___ ___| |_| | __| \r\n \ | | | | .'| | . | -_| | . | _| . | _| | |__ | \r\n \ |_|_|_|__,|_|_|___|___|_|___|_| |___|_| |_____|_____| \r\n" #endif // !__KERNELINF_H__
514
C
.h
11
40.818182
81
0.314741
petrvelicka/MandelbrotOS
3
20
0
MPL-2.0
9/7/2024, 2:19:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,967,306
string.h
petrvelicka_MandelbrotOS/src/include/string.h
#ifndef __STRING_H__ #define __STRING_H__ #define DICT_LEN 256 #include <stddef.h> #include <stdint.h> #include <stdbool.h> #include <stdarg.h> void *memset(void *b, int c, int len); unsigned int strlen(const char *s); char *strcat(char *s1, const char *s2); char *strcpy(char *destination, const char *source); char * itoa( int value, char * str, int base ); int atoi(char *str); char* dyncat(char *s1, char *s2); int strcmp(char input[],char check[]); char *strtok(char *str, char *delim); int tolower(int ch); float atof(const char *s); int isdigit(int c); int wspaceamount(char *a); void memcpy(void *dest, void *src, size_t n); #endif // !__STRING_H__
660
C
.h
22
28.863636
52
0.705512
petrvelicka/MandelbrotOS
3
20
0
MPL-2.0
9/7/2024, 2:19:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,967,308
hw.h
petrvelicka_MandelbrotOS/src/include/hw.h
#ifndef __HW_H__ #define __HW_H__ #include <stdint.h> unsigned char inb (unsigned short _port); void outb (unsigned short _port, unsigned char _data); uint16_t inw(uint16_t _port); void io_wait(void); #endif // !__HW_H__
223
C
.h
8
26.625
54
0.694836
petrvelicka/MandelbrotOS
3
20
0
MPL-2.0
9/7/2024, 2:19:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,967,309
isr.h
petrvelicka_MandelbrotOS/src/include/kernel/isr.h
#ifndef __ISR_H__ #define __ISR_H__ #include <stdint.h> extern void _isr0(); extern void _isr1(); extern void _isr2(); extern void _isr3(); extern void _isr4(); extern void _isr5(); extern void _isr6(); extern void _isr7(); extern void _isr8(); extern void _isr9(); extern void _isr10(); extern void _isr11(); extern void _isr12(); extern void _isr13(); extern void _isr14(); extern void _isr15(); extern void _isr16(); extern void _isr17(); extern void _isr18(); extern void _isr19(); extern void _isr20(); extern void _isr21(); extern void _isr22(); extern void _isr23(); extern void _isr24(); extern void _isr25(); extern void _isr26(); extern void _isr27(); extern void _isr28(); extern void _isr29(); extern void _isr30(); extern void _isr31(); typedef struct regs { uint32_t gs, fs, es, ds; uint32_t edi, esi, ebp, esp, ebx, edx, ecx, eax; uint32_t int_no, err_code; uint32_t eip, cs, eflags, useresp, ss; } register_t; int init_isr(); #endif // !__ISR_H__
979
C
.h
44
20.886364
51
0.688507
petrvelicka/MandelbrotOS
3
20
0
MPL-2.0
9/7/2024, 2:19:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,967,310
pit.h
petrvelicka_MandelbrotOS/src/include/kernel/pit.h
#ifndef __PIT_H__ #define __PIT_H__ #include <stdint.h> uint64_t timer_ticks; int init_timer(); void timer_phase(int hz); void sleep(uint64_t milliseconds); #endif // !__PIT_H__
181
C
.h
8
21.25
34
0.7
petrvelicka/MandelbrotOS
3
20
0
MPL-2.0
9/7/2024, 2:19:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,967,311
vbe.h
petrvelicka_MandelbrotOS/src/include/kernel/vbe.h
#ifndef _KERNEL_VESA_DRIVER #define _KERNEL_VESA_DRIVER #include <stdint.h> #include <multiboot.h> typedef struct rgb { uint8_t r, g, b; } argb_t __attribute__((packed)); void *fb_addr; uint32_t fb_pitch; uint32_t fb_width; uint32_t fb_height; uint8_t fb_bpp; uint32_t rgb_to_color(argb_t *); int putpixel(int x, int y, int color); int drawrect(int startx, int starty, int stopx, int stopy, int color); int drawborder(int startx, int starty, int stopx, int stopy, int thickness, int color, int incolor); void mandelbrot(float left, float top, float xside, float yside, int color); int init_vbe(multiboot_info_t * mbi); #endif
634
C
.h
20
30.3
100
0.747941
petrvelicka/MandelbrotOS
3
20
0
MPL-2.0
9/7/2024, 2:19:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,967,313
kbd.h
petrvelicka_MandelbrotOS/src/include/kernel/kbd.h
#ifndef __KBD_H__ #define __KBD_H__ #define KB_DATA 0x60 #define KB_STAT 0x64 #define KB_CMD 0x64 /* output buffer full */ #define KB_STAT_OBF 0x01 #define SHIFT (1<<0) #define CTRL (1<<1) #define ALT (1<<2) #define E0ESC (1<<6) #define LSHIFT 0x2A #define RSHIFT 0x36 #define KB_IS_RELEASE(sc) (sc & 0x80) #define KB_IS_ESCAPE(sc) (sc == 0xe0) int kbd_init(); char *gets(); char currkey; #endif // !__KBD_H__
467
C
.h
19
23.157895
40
0.613636
petrvelicka/MandelbrotOS
3
20
0
MPL-2.0
9/7/2024, 2:19:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,967,314
kshell.h
petrvelicka_MandelbrotOS/src/include/kernel/kshell.h
#ifndef __KSHELL_H__ #define __KSHELL_H__ #include <multiboot.h> #define check_cmd(c) strcmp((char*)argv[0], (char*)c) int kshell(multiboot_info_t *mbi, unsigned long magic); #endif // !__KSHELL_H__
202
C
.h
6
32.166667
55
0.689119
petrvelicka/MandelbrotOS
3
20
0
MPL-2.0
9/7/2024, 2:19:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,967,315
idt.h
petrvelicka_MandelbrotOS/src/include/kernel/idt.h
#ifndef __IDT_H__ #define __IDT_H__ #include <stdint.h> typedef struct idt_entry { uint16_t base_lo; uint16_t sel; uint8_t always0; uint8_t flags; uint16_t base_hi; } __attribute__ ((packed)) idt_entry_t; typedef struct idt_ptr { uint16_t limit; uint32_t base; } __attribute__ ((packed)) idt_ptr_t; idt_entry_t idt[256]; idt_ptr_t idtp; extern void idt_load(); int init_idt(); void idt_set_gate(uint8_t num, uint32_t base, uint16_t sel, uint8_t flags); #endif // !__IDT_H__
508
C
.h
22
20.545455
75
0.666667
petrvelicka/MandelbrotOS
3
20
0
MPL-2.0
9/7/2024, 2:19:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,967,320
init.h
petrvelicka_MandelbrotOS/src/include/kernel/init.h
#ifndef __INIT_H__ #define __INIT_H__ #include <multiboot.h> #include <stdbool.h> int inited_funs_no; const char* inited_funcs[50]; void init_check(int func, char *name, bool ness); #endif // !__INIT_H__
208
C
.h
8
24.5
49
0.69898
petrvelicka/MandelbrotOS
3
20
0
MPL-2.0
9/7/2024, 2:19:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,967,321
irq.h
petrvelicka_MandelbrotOS/src/include/kernel/irq.h
#ifndef __IRQ_H__ #define __IRQ_H__ #include <kernel/isr.h> extern void _irq0(); extern void _irq1(); extern void _irq2(); extern void _irq3(); extern void _irq4(); extern void _irq5(); extern void _irq6(); extern void _irq7(); extern void _irq8(); extern void _irq9(); extern void _irq10(); extern void _irq11(); extern void _irq12(); extern void _irq13(); extern void _irq14(); extern void _irq15(); int init_irq(); void irq_install_handler(int32_t irq, void (*handler)(register_t *r)); #endif // !__IRQ_H__
514
C
.h
22
22.181818
70
0.690574
petrvelicka/MandelbrotOS
3
20
0
MPL-2.0
9/7/2024, 2:19:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,285,390
dtkocr.h
linuxdeepin_dtkmultimedia/include/dtkocr/dtkocr.h
// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: LGPL-3.0-or-later #ifndef DOCR_NAMESPACE_H #define DOCR_NAMESPACE_H #define DOCR_NAMESPACE Dtk::Ocr #define DOCR_USE_NAMESPACE using namespace DOCR_NAMESPACE; #define DOCR_BEGIN_NAMESPACE namespace Dtk { namespace Ocr { #define DOCR_END_NAMESPACE }} #endif
362
C
.c
10
35
71
0.8
linuxdeepin/dtkmultimedia
3
16
2
LGPL-3.0
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,285,513
stream_io.c
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam_encoder/stream_io.c
/*******************************************************************************# # guvcview http://guvcview.sourceforge.net # # # # Paulo Assis <[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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # ********************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <errno.h> #include <assert.h> /* support for internationalization - i18n */ #include <locale.h> #include <libintl.h> #include "cameraconfig.h" #include "gviewencoder.h" #include "encoder.h" #include "stream_io.h" #include "gview.h" /* * get last stream of the list (list tail) * args: * stream_list - pointer to stream list * * asserts: * none * * returns: pointer to last stream of the list * or NULL if none */ stream_io_t *get_last_stream(stream_io_t *stream_list) { stream_io_t *stream = stream_list; if(!stream) return NULL; while(stream->next != NULL) stream = stream->next; return stream; } /* * add a new stream to the list * args: * stream_list - pointer to pointer of stream_list * list_size - pointer to list size * * asserts: * none * * returns: pointer to newly allocated stream */ stream_io_t *add_new_stream(stream_io_t **stream_list, int *list_size) { stream_io_t *stream = calloc(1, sizeof(stream_io_t)); if (stream == NULL) { fprintf(stderr, "ENCODER: FATAL memory allocation failure (add_new_stream): %s\n", strerror(errno)); exit(-1); } stream->next = NULL; stream->id = *list_size; fprintf(stderr, "ENCODER: add stream %i to stream list\n", stream->id); stream_io_t *last_stream = get_last_stream(*stream_list); stream->previous = last_stream; if(last_stream) last_stream->next = stream; else *stream_list = stream; /*first stream*/ stream->indexes = NULL; *list_size = *list_size + 1; return(stream); } /* * destroy the sream list (free all streams) * args: * stream_list - pointer to stream list * list_size - pointer to list size * * asserts: * none * * returns: none */ void destroy_stream_list(stream_io_t *stream_list, int *list_size) { stream_io_t *stream = get_last_stream(stream_list); while(stream != NULL) //from end to start { stream_io_t *prev_stream = stream->previous; if(stream->indexes != NULL) free(stream->indexes); free(stream); stream = prev_stream; *list_size = *list_size - 1; } } /* * get stream with index from list * args: * stream_list - pointer to pointer of stream_list * index - stream index in the list * * asserts: * none * * returns: pointer to stream */ stream_io_t *get_stream(stream_io_t *stream_list, int index) { stream_io_t *stream = stream_list; if(!stream) return NULL; int j = 0; while(stream->next != NULL && (j < index)) { stream = stream->next; j++; } if(j != index) return NULL; return stream; } /* * get first video stream * args: * stream_list - pointer to stream list * * asserts: * none * * returns: pointer to stream */ stream_io_t *get_first_video_stream(stream_io_t *stream_list) { stream_io_t *stream = stream_list; while(stream != NULL) { if(stream->type == STREAM_TYPE_VIDEO) return stream; stream = stream->next; } return NULL; } /* * get first audio stream * args: * stream_list - pointer to stream list * * asserts: * none * * returns: pointer to stream */ //stream_io_t *get_first_audio_stream(stream_io_t *stream_list) //{ // stream_io_t *stream = stream_list; // // while(stream != NULL) // { // if(stream->type == STREAM_TYPE_AUDIO) // return stream; // // stream = stream->next; // } // // return NULL; //}
5,068
C
.c
183
25.814208
102
0.573811
linuxdeepin/dtkmultimedia
3
16
2
LGPL-3.0
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
15,285,514
avi.c
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam_encoder/avi.c
/*******************************************************************************# # guvcview http://guvcview.sourceforge.net # # # # Paulo Assis <[email protected]> # # # # This is a heavily modified version of the matroska interface from x264 # # Copyright (C) 2005 Mike Matsnev # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 2 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program; if not, write to the Free Software # # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # ********************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <inttypes.h> #include <sys/types.h> #include <limits.h> #include <unistd.h> #include <fcntl.h> #include <math.h> #include <string.h> #include <errno.h> #include <assert.h> /* support for internationalization - i18n */ #include <locale.h> #include <libintl.h> #include "gviewencoder.h" #include "encoder.h" #include "stream_io.h" #include "file_io.h" #include "avi.h" #include "gview.h" #include "load_libs.h" #ifndef O_BINARY /* win32 wants a binary flag to open(); this sets it to null on platforms that don't have it. */ #define O_BINARY 0 #endif #define INFO_LIST //#define MAX_INFO_STRLEN 64 //static char id_str[MAX_INFO_STRLEN]; #ifndef PACKAGE #define PACKAGE "guvcview" #endif //#ifndef VERSION //#define VERSION "1.0" //#endif #define AVI_INDEX_CLUSTER_SIZE 16384 #define AVIF_HASINDEX 0x00000010 /* Index at end of file */ #define AVIF_MUSTUSEINDEX 0x00000020 #define AVIF_ISINTERLEAVED 0x00000100 #define AVIF_TRUSTCKTYPE 0x00000800 /* Use CKType to find key frames */ #define AVIF_WASCAPTUREFILE 0x00010000 #define AVIF_COPYRIGHTED 0x00020000 #define AVI_MAX_RIFF_SIZE 0x40000000LL /*1Gb = 0x40000000LL*/ #define AVI_MASTER_INDEX_SIZE 256 #define AVI_MAX_STREAM_COUNT 10 /* index flags */ #define AVIF_INDEX 0x10 // bIndexType codes // #define AVI_INDEX_OF_INDEXES 0x00 // when each entry in aIndex // array points to an index chunk #define AVI_INDEX_OF_CHUNKS 0x01 // when each entry in aIndex // array points to a chunk in the file #define AVI_INDEX_IS_DATA 0x80 // when each entry is aIndex is // really the data // bIndexSubtype codes for INDEX_OF_CHUNKS #define AVI_INDEX_2FIELD 0x01 // when fields within frames // are also indexed extern int verbosity; int64_t avi_open_tag (avi_context_t *avi_ctx, const char *tag) { io_write_4cc(avi_ctx->writer, tag); io_write_wl32(avi_ctx->writer, 0); return io_get_offset(avi_ctx->writer); } static void avi_close_tag(avi_context_t *avi_ctx, int64_t start_pos) { int64_t current_offset = io_get_offset(avi_ctx->writer); int32_t size = (int32_t) (current_offset - start_pos); io_seek(avi_ctx->writer, start_pos-4); io_write_wl32(avi_ctx->writer, (uint32_t)size); io_seek(avi_ctx->writer, current_offset); if(verbosity > 0) printf("ENCODER: (avi) %" PRIu64 " closing tag at %" PRIu64 " with size %i\n", current_offset, start_pos-4, size); } /* * Calculate audio sample size from number of bits and number of channels. * This may have to be adjusted for eg. 12 bits and stereo */ static int avi_audio_sample_size(stream_io_t *stream) { if(stream->type != STREAM_TYPE_AUDIO) return -1; int s; if (stream->a_fmt != WAVE_FORMAT_PCM) { s = 4; } else { s = ((stream->a_bits+7)/8)*stream->a_chans; if(s<4) s=4; /* avoid possible zero divisions */ } return s; } static char* avi_stream2fourcc(char* tag, stream_io_t *stream) { tag[0] = '0' + (char)((stream->id)/10); tag[1] = '0' + (stream->id)%10; switch(stream->type) { case STREAM_TYPE_VIDEO: tag[2] = 'd'; tag[3] = 'c'; break; case STREAM_TYPE_SUB: // note: this is not an official code tag[2] = 's'; tag[3] = 'b'; break; default: //audio tag[2] = 'w'; tag[3] = 'b'; break; } tag[4] = '\0'; return tag; } void avi_put_main_header(avi_context_t *avi_ctx, avi_riff_t *riff) { avi_ctx->fps = get_first_video_stream(avi_ctx->stream_list)->fps; int width = get_first_video_stream(avi_ctx->stream_list)->width; int height = get_first_video_stream(avi_ctx->stream_list)->height; int time_base_num = avi_ctx->time_base_num; int time_base_den = avi_ctx->time_base_den; uint32_t data_rate = 0; if(time_base_den > 0 || time_base_num > 0) //these are not set yet so it's always false data_rate = (uint32_t) (INT64_C(1000000) * time_base_num/time_base_den); else fprintf(stderr, "ENCODER: (avi) bad time base (%i/%i): set it later", time_base_num, time_base_den); /*do not force index yet -only when closing*/ /*this should prevent bad avi files even if it is not closed properly*/ //if(hasIndex) flag |= AVIF_HASINDEX; //if(hasIndex && avi_ctx->must_use_index) flag |= AVIF_MUSTUSEINDEX; avi_ctx->avi_flags = AVIF_WASCAPTUREFILE; int64_t avih = avi_open_tag(avi_ctx, "avih"); // main avi header riff->time_delay_off = io_get_offset(avi_ctx->writer); io_write_wl32(avi_ctx->writer, 1000000 / FRAME_RATE_SCALE); // time per frame (milisec) io_write_wl32(avi_ctx->writer, data_rate); // data rate io_write_wl32(avi_ctx->writer, 0); // Padding multiple size (2048) io_write_wl32(avi_ctx->writer, avi_ctx->avi_flags); // parameter Flags //riff->frames_hdr_all = io_get_offset(avi_ctx->writer); io_write_wl32(avi_ctx->writer, 0); // number of video frames io_write_wl32(avi_ctx->writer, 0); // number of preview frames io_write_wl32(avi_ctx->writer, (uint32_t)avi_ctx->stream_list_size); // number of data streams (audio + video)*/ io_write_wl32(avi_ctx->writer, 1024*1024); // suggested playback buffer size (bytes) io_write_wl32(avi_ctx->writer, (uint32_t)width); // width io_write_wl32(avi_ctx->writer, (uint32_t)height); // height io_write_wl32(avi_ctx->writer, 0); // time scale: unit used to measure time (30) io_write_wl32(avi_ctx->writer, 0); // data rate (frame rate * time scale) io_write_wl32(avi_ctx->writer, 0); // start time (0) io_write_wl32(avi_ctx->writer, 0); // size of avi data chunk (in scale units) avi_close_tag(avi_ctx, avih); //write the chunk size } int64_t avi_put_bmp_header(avi_context_t *avi_ctx, stream_io_t *stream) { int frate = 15 * FRAME_RATE_SCALE; if(stream->fps > 0.001) frate = (int) ((FRAME_RATE_SCALE * (stream->fps)) + 0.5); int64_t strh = avi_open_tag(avi_ctx, "strh");// video stream header io_write_4cc(avi_ctx->writer, "vids"); // stream type io_write_4cc(avi_ctx->writer, stream->compressor); // Handler (VIDEO CODEC) io_write_wl32(avi_ctx->writer, 0); // Flags io_write_wl16(avi_ctx->writer, 0); // stream priority io_write_wl16(avi_ctx->writer, 0); // language tag io_write_wl32(avi_ctx->writer, 0); // initial frames io_write_wl32(avi_ctx->writer, FRAME_RATE_SCALE); // Scale stream->rate_hdr_strm = io_get_offset(avi_ctx->writer); //store this to set proper fps io_write_wl32(avi_ctx->writer, (uint32_t)frate); // Rate: Rate/Scale == sample/second (fps) */ io_write_wl32(avi_ctx->writer, 0); // start time stream->frames_hdr_strm = io_get_offset(avi_ctx->writer); io_write_wl32(avi_ctx->writer, 0); // lenght of stream io_write_wl32(avi_ctx->writer, 1024*1024); // suggested playback buffer size io_write_wl32(avi_ctx->writer, (uint32_t)(-1)); // Quality io_write_wl32(avi_ctx->writer, 0); // SampleSize io_write_wl16(avi_ctx->writer, 0); // rFrame (left) io_write_wl16(avi_ctx->writer, 0); // rFrame (top) io_write_wl16(avi_ctx->writer, (uint16_t)stream->width); // rFrame (right) io_write_wl16(avi_ctx->writer, (uint16_t)stream->height); // rFrame (bottom) avi_close_tag(avi_ctx, strh); //write the chunk size return strh; } int64_t avi_put_wav_header(avi_context_t *avi_ctx, stream_io_t *stream) { int sampsize = avi_audio_sample_size(stream); int64_t strh = avi_open_tag(avi_ctx, "strh");// audio stream header io_write_4cc(avi_ctx->writer, "auds"); io_write_wl32(avi_ctx->writer, 1); // codec tag on strf io_write_wl32(avi_ctx->writer, 0); // Flags io_write_wl16(avi_ctx->writer, 0); // stream priority io_write_wl16(avi_ctx->writer, 0); // language tag io_write_wl32(avi_ctx->writer, 0); // initial frames stream->rate_hdr_strm = io_get_offset(avi_ctx->writer); io_write_wl32(avi_ctx->writer, (uint32_t)(sampsize/4)); // Scale io_write_wl32(avi_ctx->writer, (uint32_t)(stream->mpgrate/8)); // Rate: Rate/Scale == sample/second (fps) */ io_write_wl32(avi_ctx->writer, 0); // start time stream->frames_hdr_strm = io_get_offset(avi_ctx->writer); io_write_wl32(avi_ctx->writer, 0); // lenght of stream io_write_wl32(avi_ctx->writer, 12*1024); // suggested playback buffer size io_write_wl32(avi_ctx->writer, (uint32_t)(-1)); // Quality io_write_wl32(avi_ctx->writer,(uint32_t)( sampsize/4)); // SampleSize io_write_wl16(avi_ctx->writer, 0); // rFrame (left) io_write_wl16(avi_ctx->writer, 0); // rFrame (top) io_write_wl16(avi_ctx->writer, 0); // rFrame (right) io_write_wl16(avi_ctx->writer, 0); // rFrame (bottom) avi_close_tag(avi_ctx, strh); //write the chunk size return strh; } void avi_put_vstream_format_header(avi_context_t *avi_ctx, stream_io_t *stream) { int vxd_size = stream->extra_data_size; int vxd_size_align = (stream->extra_data_size+1) & ~1; int64_t strf = avi_open_tag(avi_ctx, "strf"); // stream format header io_write_wl32(avi_ctx->writer, (uint32_t)(40 + vxd_size)); // sruct Size io_write_wl32(avi_ctx->writer,(uint32_t) stream->width); // Width io_write_wl32(avi_ctx->writer, (uint32_t)stream->height); // Height io_write_wl16(avi_ctx->writer, 1); // Planes io_write_wl16(avi_ctx->writer, 24); // Count - bitsperpixel - 1,4,8 or 24 32 if(strncmp(stream->compressor,"DIB",3)==0) io_write_wl32(avi_ctx->writer, 0); // Compression else io_write_4cc(avi_ctx->writer, stream->compressor); io_write_wl32(avi_ctx->writer, (uint32_t)(stream->width*stream->height*3));// image size (in bytes?) io_write_wl32(avi_ctx->writer, 0); // XPelsPerMeter io_write_wl32(avi_ctx->writer, 0); // YPelsPerMeter io_write_wl32(avi_ctx->writer, 0); // ClrUsed: Number of colors used io_write_wl32(avi_ctx->writer, 0); // ClrImportant: Number of colors important // write extradata (codec private) if (vxd_size > 0 && stream->extra_data) { io_write_buf(avi_ctx->writer, stream->extra_data, vxd_size); if (vxd_size != vxd_size_align) { io_write_w8(avi_ctx->writer, 0); //align } } avi_close_tag(avi_ctx, strf); //write the chunk size } void avi_put_astream_format_header(avi_context_t *avi_ctx, stream_io_t *stream) { int axd_size = stream->extra_data_size; int axd_size_align = (stream->extra_data_size+1) & ~1; int sampsize = avi_audio_sample_size(stream); int64_t strf = avi_open_tag(avi_ctx, "strf");// audio stream format io_write_wl16(avi_ctx->writer, (uint16_t)stream->a_fmt); // Format (codec) tag io_write_wl16(avi_ctx->writer, (uint16_t)stream->a_chans); // Number of channels io_write_wl32(avi_ctx->writer, (uint32_t)stream->a_rate); // SamplesPerSec io_write_wl32(avi_ctx->writer, (uint32_t)stream->mpgrate/8);// Average Bytes per sec io_write_wl16(avi_ctx->writer, (uint16_t)sampsize/4); // BlockAlign io_write_wl16(avi_ctx->writer, (uint16_t)stream->a_bits); //BitsPerSample io_write_wl16(avi_ctx->writer, (uint16_t)axd_size); //size of extra data // write extradata (codec private) if (axd_size > 0 && stream->extra_data) { io_write_buf(avi_ctx->writer, stream->extra_data, axd_size); if (axd_size != axd_size_align) { io_write_w8(avi_ctx->writer, 0); //align } } avi_close_tag(avi_ctx, strf); //write the chunk size } void avi_put_vproperties_header(avi_context_t *avi_ctx, stream_io_t *stream) { uint32_t refresh_rate = (uint32_t) lrintf((float)(2.0 * avi_ctx->fps)); if(avi_ctx->time_base_den > 0 || avi_ctx->time_base_num > 0) //these are not set yet so it's always false { double time_base = avi_ctx->time_base_num / (double) avi_ctx->time_base_den; refresh_rate = (uint32_t)lrintf((float)(1.0/time_base)); } int vprp= (int)avi_open_tag(avi_ctx, "vprp"); io_write_wl32(avi_ctx->writer, 0); //video format = unknown io_write_wl32(avi_ctx->writer, 0); //video standard= unknown io_write_wl32(avi_ctx->writer, refresh_rate); // dwVerticalRefreshRate io_write_wl32(avi_ctx->writer, (uint32_t)stream->width ); //horizontal pixels io_write_wl32(avi_ctx->writer, (uint32_t)stream->height); //vertical lines io_write_wl16(avi_ctx->writer, (uint16_t)stream->height); //Active Frame Aspect Ratio (4:3 - 16:9) io_write_wl16(avi_ctx->writer, (uint16_t)stream->width); //Active Frame Aspect Ratio io_write_wl32(avi_ctx->writer, (uint32_t)stream->width ); //Active Frame Height in Pixels io_write_wl32(avi_ctx->writer, (uint32_t)stream->height); //Active Frame Height in Lines io_write_wl32(avi_ctx->writer, 1); //progressive FIXME //Field Framing Information io_write_wl32(avi_ctx->writer, (uint32_t)stream->height); io_write_wl32(avi_ctx->writer,(uint32_t) stream->width ); io_write_wl32(avi_ctx->writer, (uint32_t)stream->height); io_write_wl32(avi_ctx->writer, (uint32_t)stream->width ); io_write_wl32(avi_ctx->writer, 0); io_write_wl32(avi_ctx->writer, 0); io_write_wl32(avi_ctx->writer, 0); io_write_wl32(avi_ctx->writer, 0); avi_close_tag(avi_ctx, vprp); } int64_t avi_create_riff_tags(avi_context_t *avi_ctx, avi_riff_t *riff) { int64_t off = 0; riff->riff_start = avi_open_tag(avi_ctx, "RIFF"); if(riff->id == 1) { io_write_4cc(avi_ctx->writer, "AVI "); off = avi_open_tag(avi_ctx, "LIST"); io_write_4cc(avi_ctx->writer, "hdrl"); } else { io_write_4cc(avi_ctx->writer, "AVIX"); off = avi_open_tag(avi_ctx, "LIST"); io_write_4cc(avi_ctx->writer, "movi"); riff->movi_list = off; //update movi list pos for this riff } return off; } //only for riff id = 1 void avi_create_riff_header(avi_context_t *avi_ctx, avi_riff_t *riff) { int64_t list1 = avi_create_riff_tags(avi_ctx, riff); avi_put_main_header(avi_ctx, riff); int i, j = 0; for(j=0; j< avi_ctx->stream_list_size; j++) { stream_io_t *stream = get_stream(avi_ctx->stream_list, j); int64_t list2 = avi_open_tag(avi_ctx, "LIST"); io_write_4cc(avi_ctx->writer,"strl"); //stream list if(stream->type == STREAM_TYPE_VIDEO) { avi_put_bmp_header(avi_ctx, stream); avi_put_vstream_format_header(avi_ctx, stream); } else { avi_put_wav_header(avi_ctx, stream); avi_put_astream_format_header(avi_ctx, stream); } /* Starting to lay out AVI OpenDML master index. * We want to make it JUNK entry for now, since we'd * like to get away without making AVI an OpenDML one * for compatibility reasons. */ char tag[5]; avi_index_t *indexes = (avi_index_t *) stream->indexes; indexes->entry = indexes->ents_allocated = 0; indexes->indx_start = io_get_offset(avi_ctx->writer); int64_t ix = avi_open_tag(avi_ctx, "JUNK"); // ’ix##’ io_write_wl16(avi_ctx->writer, 4); // wLongsPerEntry must be 4 (size of each entry in aIndex array) io_write_w8(avi_ctx->writer, 0); // bIndexSubType must be 0 (frame index) or AVI_INDEX_2FIELD io_write_w8(avi_ctx->writer, AVI_INDEX_OF_INDEXES); // bIndexType (0 == AVI_INDEX_OF_INDEXES) io_write_wl32(avi_ctx->writer, 0); // nEntriesInUse (will fill out later on) io_write_4cc(avi_ctx->writer, avi_stream2fourcc(tag, stream)); // dwChunkId io_write_wl32(avi_ctx->writer, 0); // dwReserved[3] must be 0 io_write_wl32(avi_ctx->writer, 0); io_write_wl32(avi_ctx->writer, 0); for (i=0; i < AVI_MASTER_INDEX_SIZE; i++) { io_write_wl64(avi_ctx->writer, 0); // absolute file offset, offset 0 is unused entry io_write_wl32(avi_ctx->writer, 0); // dwSize - size of index chunk at this offset io_write_wl32(avi_ctx->writer, 0); // dwDuration - time span in stream ticks } avi_close_tag(avi_ctx, ix); //write the chunk size if(stream->type == STREAM_TYPE_VIDEO) avi_put_vproperties_header(avi_ctx, stream); avi_close_tag(avi_ctx, list2); //write the chunk size } avi_ctx->odml_list = avi_open_tag(avi_ctx, "JUNK"); io_write_4cc(avi_ctx->writer, "odml"); io_write_4cc(avi_ctx->writer, "dmlh"); io_write_wl32(avi_ctx->writer, 248); for (i = 0; i < 248; i+= 4) io_write_wl32(avi_ctx->writer, 0); avi_close_tag(avi_ctx, avi_ctx->odml_list); avi_close_tag(avi_ctx, list1); //write the chunk size /* some padding for easier tag editing */ int64_t list3 = avi_open_tag(avi_ctx, "JUNK"); for (i = 0; i < 1016; i += 4) io_write_wl32(avi_ctx->writer, 0); avi_close_tag(avi_ctx, list3); //write the chunk size riff->movi_list = avi_open_tag(avi_ctx, "LIST"); io_write_4cc(avi_ctx->writer, "movi"); } avi_riff_t *avi_get_last_riff(avi_context_t *avi_ctx) { avi_riff_t *last_riff = avi_ctx->riff_list; while(last_riff->next != NULL) last_riff = last_riff->next; return last_riff; } avi_riff_t *avi_get_riff(avi_context_t *avi_ctx, int index) { avi_riff_t *riff = avi_ctx->riff_list; if(!riff) return NULL; int j = 1; while(riff->next != NULL && (j < index)) { riff = riff->next; j++; } if(j != index) return NULL; return riff; } static void clean_indexes(avi_context_t *avi_ctx) { int i=0, j=0; for (i=0; i<avi_ctx->stream_list_size; i++) { stream_io_t *stream = get_stream(avi_ctx->stream_list, i); avi_index_t *indexes = (avi_index_t *) stream->indexes; for (j=0; j<indexes->ents_allocated/AVI_INDEX_CLUSTER_SIZE; j++) free(indexes->cluster[j]); getAvutil()->m_av_freep(&indexes->cluster); indexes->ents_allocated = indexes->entry = 0; } } //call this after adding all the streams avi_riff_t *avi_add_new_riff(avi_context_t *avi_ctx) { avi_riff_t *riff = calloc(1, sizeof(avi_riff_t)); if(riff == NULL) { fprintf(stderr, "ENCODER: FATAL memory allocation failure (avi_add_new_riff): %s\n", strerror(errno)); exit(-1); } riff->next = NULL; riff->id = avi_ctx->riff_list_size + 1; if(riff->id == 1) { riff->previous = NULL; avi_ctx->riff_list = riff; avi_create_riff_header(avi_ctx, riff); } else { avi_riff_t *last_riff = avi_get_last_riff(avi_ctx); riff->previous = last_riff; last_riff->next = riff; avi_create_riff_tags(avi_ctx, riff); } avi_ctx->riff_list_size++; clean_indexes(avi_ctx); if(verbosity > 0) printf("ENCODER: (avi) adding new RIFF (%i)\n", riff->id); return riff; } //second function to get called (add video stream to avi_Context) stream_io_t *avi_add_video_stream( avi_context_t *avi_ctx, int32_t width, int32_t height, int32_t fps, int32_t fps_num, int32_t codec_id) { stream_io_t *stream = add_new_stream(&avi_ctx->stream_list, &avi_ctx->stream_list_size); stream->type = STREAM_TYPE_VIDEO; stream->fps = (double) fps/fps_num; stream->width = width; stream->height = height; stream->codec_id = codec_id; stream->indexes = (void *) calloc(1, sizeof(avi_index_t)); if(stream->indexes == NULL) { fprintf(stderr, "ENCODER: FATAL memory allocation failure (avi_add_video_stream): %s\n", strerror(errno)); exit(-1); } int codec_ind = get_video_codec_list_index(codec_id); strncpy(stream->compressor, encoder_get_video_codec_4cc(codec_ind), 8); return stream; } //third function to get called (add audio stream to avi_Context) stream_io_t *avi_add_audio_stream( avi_context_t *avi_ctx, int32_t channels, int32_t rate, int32_t bits, int32_t mpgrate, int32_t codec_id, int32_t format) { stream_io_t *stream = add_new_stream(&avi_ctx->stream_list, &avi_ctx->stream_list_size); stream->type = STREAM_TYPE_AUDIO; stream->a_chans = channels; stream->a_rate = rate; stream->a_bits = bits; stream->mpgrate = mpgrate; stream->a_vbr = 0; stream->codec_id = codec_id; stream->a_fmt = format; stream->indexes = (void *) calloc(1, sizeof(avi_index_t)); if(stream->indexes == NULL) { fprintf(stderr, "ENCODER: FATAL memory allocation failure (avi_add_audio_stream): %s\n", strerror(errno)); exit(-1); } return stream; } /* first function to get called avi_create_context: Open an AVI File and write a bunch of zero bytes as space for the header. Creates a mutex. returns a pointer to avi_Context on success, a NULL pointer on error */ avi_context_t *avi_create_context(const char *filename) { avi_context_t *avi_ctx = calloc(1, sizeof(avi_context_t)); if(avi_ctx == NULL) { fprintf(stderr, "ENCODER: FATAL memory allocation failure (avi_create_context): %s\n", strerror(errno)); exit(-1); } avi_ctx->writer = io_create_writer(filename, 0); if (avi_ctx->writer == NULL) { fprintf(stderr, "ENCODER: (avi) Could not open file (%s) for writing: %s", filename, strerror(errno)); free(avi_ctx); return NULL; } avi_ctx->flags = 0; /*recordind*/ avi_ctx->riff_list = NULL; avi_ctx->riff_list_size = 0; avi_ctx->stream_list = NULL; avi_ctx->stream_list_size = 0; return avi_ctx; } void avi_destroy_context(avi_context_t *avi_ctx) { //clean up io_destroy_writer(avi_ctx->writer); avi_riff_t *riff = avi_get_last_riff(avi_ctx); while(riff != NULL) //from end to start { avi_riff_t *prev_riff = riff->previous; free(riff); riff = prev_riff; avi_ctx->riff_list_size--; } destroy_stream_list(avi_ctx->stream_list, &avi_ctx->stream_list_size); //free avi_Context free(avi_ctx); } avi_I_entry_t *avi_get_ientry(avi_index_t *idx, int ent_id) { int cl = ent_id / AVI_INDEX_CLUSTER_SIZE; int id = ent_id % AVI_INDEX_CLUSTER_SIZE; return &idx->cluster[cl][id]; } static int avi_write_counters(avi_context_t *avi_ctx, __attribute__((unused))avi_riff_t *riff) { int n, nb_frames = 0; io_flush_buffer(avi_ctx->writer); //int time_base_num = avi_ctx->time_base_num; //int time_base_den = avi_ctx->time_base_den; int64_t file_size = io_get_offset(avi_ctx->writer);//avi_tell(avi_ctx); if(verbosity > 0) printf("ENCODER: (avi) file size = %" PRIu64 "\n", file_size); for(n = 0; n < avi_ctx->stream_list_size; n++) { stream_io_t *stream = get_stream(avi_ctx->stream_list, n); if(stream->rate_hdr_strm <= 0) { fprintf(stderr, "ENCODER: (avi) stream rate header pos not valid\n"); } else { io_seek(avi_ctx->writer, stream->rate_hdr_strm); if(stream->type == STREAM_TYPE_VIDEO && avi_ctx->fps > 0.001) { uint32_t rate =(uint32_t) FRAME_RATE_SCALE * (uint32_t)lrintf((float)avi_ctx->fps); if(verbosity > 0) fprintf(stderr,"ENCODER: (avi) storing rate(%u)\n",rate); io_write_wl32(avi_ctx->writer, rate); } } if(stream->frames_hdr_strm <= 0) { fprintf(stderr, "ENCODER: (avi) stream frames header pos not valid\n"); } else { io_seek(avi_ctx->writer, stream->frames_hdr_strm); if(stream->type == STREAM_TYPE_VIDEO) { io_write_wl32(avi_ctx->writer, stream->packet_count); nb_frames = (int)MAX((uint32_t)nb_frames, stream->packet_count); } else { int sampsize = avi_audio_sample_size(stream); io_write_wl32(avi_ctx->writer, (uint32_t)(4*stream->audio_strm_length/(size_t)sampsize)); } } } avi_riff_t *riff_1 = avi_get_riff(avi_ctx, 1); if(riff_1->id == 1) /*should always be true*/ { if(riff_1->time_delay_off <= 0) { fprintf(stderr, "ENCODER: (avi) riff main header pos not valid\n"); } else { uint32_t us_per_frame = 1000; //us if(avi_ctx->fps > 0.001) us_per_frame=(uint32_t) lrintf((float)(1000000.0 / avi_ctx->fps)); avi_ctx->avi_flags |= AVIF_HASINDEX; io_seek(avi_ctx->writer, riff_1->time_delay_off); io_write_wl32(avi_ctx->writer, us_per_frame); // time_per_frame io_write_wl32(avi_ctx->writer, 0); // data rate io_write_wl32(avi_ctx->writer, 0); // Padding multiple size (2048) io_write_wl32(avi_ctx->writer, avi_ctx->avi_flags); // parameter Flags //io_seek(avi_ctx->writer, riff_1->frames_hdr_all); io_write_wl32(avi_ctx->writer, (uint32_t)nb_frames); } } //return to position (EOF) io_seek(avi_ctx->writer, file_size); return 0; } static int avi_write_ix(avi_context_t *avi_ctx) { char tag[5]; char ix_tag[] = "ix00"; int i, j; avi_riff_t *riff = avi_get_last_riff(avi_ctx); if (riff->id > AVI_MASTER_INDEX_SIZE) return -1; for (i=0;i<avi_ctx->stream_list_size;i++) { stream_io_t *stream = get_stream(avi_ctx->stream_list, i); int64_t ix, pos; avi_stream2fourcc(tag, stream); ix_tag[3] = '0' + (char)i; /*only 10 streams supported*/ /* Writing AVI OpenDML leaf index chunk */ ix = io_get_offset(avi_ctx->writer); io_write_4cc(avi_ctx->writer, ix_tag); /* ix?? */ avi_index_t *indexes = (avi_index_t *) stream->indexes; io_write_wl32(avi_ctx->writer, (uint32_t)(indexes->entry * 8 + 24)); /* chunk size */ io_write_wl16(avi_ctx->writer, 2); /* wLongsPerEntry */ io_write_w8(avi_ctx->writer, 0); /* bIndexSubType (0 == frame index) */ io_write_w8(avi_ctx->writer, AVI_INDEX_OF_CHUNKS); /* bIndexType (1 == AVI_INDEX_OF_CHUNKS) */ io_write_wl32(avi_ctx->writer, (uint32_t)indexes->entry); /* nEntriesInUse */ io_write_4cc(avi_ctx->writer, tag); /* dwChunkId */ io_write_wl64(avi_ctx->writer, (uint64_t)riff->movi_list);/* qwBaseOffset */ io_write_wl32(avi_ctx->writer, 0); /* dwReserved_3 (must be 0) */ for (j=0; j< indexes->entry; j++) { avi_I_entry_t *ie = avi_get_ientry(indexes, j); io_write_wl32(avi_ctx->writer, ie->pos + 8); io_write_wl32(avi_ctx->writer, ((uint32_t)ie->len & ~0x80000000) | (ie->flags & 0x10 ? 0 : 0x80000000)); } io_flush_buffer(avi_ctx->writer); pos = io_get_offset(avi_ctx->writer); //current position if(verbosity > 0) printf("ENCODER: (avi) wrote ix %s with %i entries\n", tag, indexes->entry); /* Updating one entry in the AVI OpenDML master index */ io_seek(avi_ctx->writer, indexes->indx_start); io_write_4cc(avi_ctx->writer, "indx"); /* enabling this entry */ io_skip(avi_ctx->writer, 8); io_write_wl32(avi_ctx->writer, (uint32_t)(riff->id)); /* nEntriesInUse */ io_skip(avi_ctx->writer, 16*(riff->id)); io_write_wl64(avi_ctx->writer,(uint64_t) ix); /* qwOffset */ io_write_wl32(avi_ctx->writer, (uint32_t)(pos - ix)); /* dwSize */ io_write_wl32(avi_ctx->writer,(uint32_t)(indexes->entry)); /* dwDuration */ //return to position io_seek(avi_ctx->writer, pos); } return 0; } static int avi_write_idx1(avi_context_t *avi_ctx, avi_riff_t *riff) { int64_t idx_chunk; int i; char tag[5]; stream_io_t *stream; avi_I_entry_t *ie = 0, *tie; int empty, stream_id = -1; idx_chunk = avi_open_tag(avi_ctx, "idx1"); for (i=0;i<avi_ctx->stream_list_size;i++) { stream = get_stream(avi_ctx->stream_list, i); stream->entry=0; } do { empty = 1; for (i=0;i<avi_ctx->stream_list_size;i++) { stream = get_stream(avi_ctx->stream_list, i); avi_index_t *indexes = (avi_index_t *) stream->indexes; if (indexes->entry <= stream->entry) continue; tie = avi_get_ientry(indexes, stream->entry); if (empty || tie->pos < ie->pos) { ie = tie; stream_id = i; } empty = 0; } if (!empty) { stream = get_stream(avi_ctx->stream_list, stream_id); avi_stream2fourcc(tag, stream); io_write_4cc(avi_ctx->writer, tag); io_write_wl32(avi_ctx->writer, ie->flags); io_write_wl32(avi_ctx->writer, ie->pos); io_write_wl32(avi_ctx->writer, ie->len); stream->entry++; } } while (!empty); avi_close_tag(avi_ctx, idx_chunk); if(verbosity > 0) printf("ENCODER: (avi) wrote idx1\n"); avi_write_counters(avi_ctx, riff); return 0; } int avi_write_packet( avi_context_t *avi_ctx, int stream_index, uint8_t *data, uint32_t size, __attribute__((unused)) int64_t dts, __attribute__((unused)) int block_align, int32_t flags) { char tag[5]; unsigned int i_flags=0; stream_io_t *stream= get_stream(avi_ctx->stream_list, stream_index); avi_riff_t *riff = avi_get_last_riff(avi_ctx); //align //while(block_align==0 && dts != AV_NOPTS_VALUE && dts > stream->packet_count) // avi_write_packet(avi_ctx, stream_index, NULL, 0, AV_NOPTS_VALUE, 0, 0); stream->packet_count++; // Make sure to put an OpenDML chunk when the file size exceeds the limits if (io_get_offset(avi_ctx->writer) - riff->riff_start > AVI_MAX_RIFF_SIZE) { avi_write_ix(avi_ctx); avi_close_tag(avi_ctx, riff->movi_list); if (riff->id == 1) avi_write_idx1(avi_ctx, riff); avi_close_tag(avi_ctx, riff->riff_start); avi_add_new_riff(avi_ctx); riff = avi_get_last_riff(avi_ctx); //update riff } avi_stream2fourcc(tag, stream); if(flags & AV_PKT_FLAG_KEY) //key frame i_flags = 0x10; if (stream->type == STREAM_TYPE_AUDIO) stream->audio_strm_length += size; avi_index_t *idx = (avi_index_t *) stream->indexes; int cl = idx->entry / AVI_INDEX_CLUSTER_SIZE; int id = idx->entry % AVI_INDEX_CLUSTER_SIZE; if (idx->ents_allocated <= idx->entry) { idx->cluster = realloc(idx->cluster, (size_t)(cl+1)*sizeof(void*)); if (idx->cluster == NULL) { fprintf(stderr, "ENCODER: FATAL memory allocation failure (avi_write_packet): %s\n", strerror(errno)); exit(-1); } idx->cluster[cl] = calloc(AVI_INDEX_CLUSTER_SIZE, sizeof(avi_I_entry_t)); if (idx->cluster[cl] == NULL) { fprintf(stderr, "ENCODER: FATAL memory allocation failure (avi_write_packet): %s\n", strerror(errno)); exit(-1); } idx->ents_allocated += AVI_INDEX_CLUSTER_SIZE; } idx->cluster[cl][id].flags = i_flags; idx->cluster[cl][id].pos = (unsigned int)(io_get_offset(avi_ctx->writer) - riff->movi_list); idx->cluster[cl][id].len = size; idx->entry++; io_write_4cc(avi_ctx->writer, tag); io_write_wl32(avi_ctx->writer, size); io_write_buf(avi_ctx->writer, data, (int)size); if (size & 1) io_write_w8(avi_ctx->writer, 0); io_flush_buffer(avi_ctx->writer); return 0; } int avi_close(avi_context_t *avi_ctx) { int res = 0; int64_t file_size; avi_riff_t *riff = avi_get_last_riff(avi_ctx); if (riff->id == 1) { avi_close_tag(avi_ctx, riff->movi_list); if(verbosity > 0) printf("ENCODER: (avi) %" PRIu64 " close movi tag\n",io_get_offset(avi_ctx->writer)); res = avi_write_idx1(avi_ctx, riff); avi_close_tag(avi_ctx, riff->riff_start); } else { avi_write_ix(avi_ctx); avi_close_tag(avi_ctx, riff->movi_list); avi_close_tag(avi_ctx, riff->riff_start); file_size = io_get_offset(avi_ctx->writer); io_seek(avi_ctx->writer, avi_ctx->odml_list - 8); io_write_4cc(avi_ctx->writer, "LIST"); /* Making this AVI OpenDML one */ io_skip(avi_ctx->writer, 16); int n = 0; int nb_frames = 0; for (n=nb_frames=0;n<avi_ctx->stream_list_size;n++) { stream_io_t *stream = get_stream(avi_ctx->stream_list, n); if (stream->type == STREAM_TYPE_VIDEO) { if (nb_frames < (int)stream->packet_count) nb_frames = (int)stream->packet_count; } else { if (stream->codec_id == AV_CODEC_ID_MP2 || stream->codec_id == AV_CODEC_ID_MP3) nb_frames += stream->packet_count; } } io_write_wl32(avi_ctx->writer, (uint32_t)nb_frames); io_seek(avi_ctx->writer, file_size); avi_write_counters(avi_ctx, riff); } clean_indexes(avi_ctx); return res; }
34,726
C
.c
854
36.314988
116
0.610834
linuxdeepin/dtkmultimedia
3
16
2
LGPL-3.0
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
15,285,516
encoder.h
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam_encoder/encoder.h
/*******************************************************************************# # guvcview http://guvcview.sourceforge.net # # # # Paulo Assis <[email protected]> # # George Sedov <[email protected]> # # - Threaded encoding # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 2 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program; if not, write to the Free Software # # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # ********************************************************************************/ #ifndef ENCODER_H #define ENCODER_H #include <inttypes.h> #include <sys/types.h> #include "cameraconfig.h" #ifdef HAVE_FFMPEG_AVCODEC_H #include <ffmpeg/avcodec.h> #else #include <libavcodec/avcodec.h> #ifdef HAVE_LIBAVUTIL_VERSION_H #include <libavutil/version.h> #endif #include <libavutil/avutil.h> #endif #define LIBAVCODEC_VER_AT_LEAST(major,minor) (LIBAVCODEC_VERSION_MAJOR > major || \ (LIBAVCODEC_VERSION_MAJOR == major && \ LIBAVCODEC_VERSION_MINOR >= minor)) #ifdef LIBAVUTIL_VERSION_MAJOR #define LIBAVUTIL_VER_AT_LEAST(major,minor) (LIBAVUTIL_VERSION_MAJOR > major || \ (LIBAVUTIL_VERSION_MAJOR == major && \ LIBAVUTIL_VERSION_MINOR >= minor)) #else #define LIBAVUTIL_VER_AT_LEAST(major,minor) 0 #endif #ifndef X264_ME_HEX #define X264_ME_HEX 1 #endif #if !LIBAVUTIL_VER_AT_LEAST(52,0) #define AV_PIX_FMT_NONE PIX_FMT_NONE #define AV_PIX_FMT_YUVJ420P PIX_FMT_YUVJ420P #define AV_PIX_FMT_YUV420P PIX_FMT_YUV420P #endif /* Possible Audio formats */ #define WAVE_FORMAT_UNKNOWN (0x0000) #define WAVE_FORMAT_PCM (0x0001) #define WAVE_FORMAT_ADPCM (0x0002) #define WAVE_FORMAT_IEEE_FLOAT (0x0003) #define WAVE_FORMAT_IBM_CVSD (0x0005) #define WAVE_FORMAT_ALAW (0x0006) #define WAVE_FORMAT_MULAW (0x0007) #define WAVE_FORMAT_OKI_ADPCM (0x0010) #define WAVE_FORMAT_DVI_ADPCM (0x0011) #define WAVE_FORMAT_DIGISTD (0x0015) #define WAVE_FORMAT_DIGIFIX (0x0016) #define WAVE_FORMAT_YAMAHA_ADPCM (0x0020) #define WAVE_FORMAT_DSP_TRUESPEECH (0x0022) #define WAVE_FORMAT_GSM610 (0x0031) #define WAVE_FORMAT_MP3 (0x0055) #define WAVE_FORMAT_MPEG12 (0x0050) #define WAVE_FORMAT_AAC (0x00ff) #define WAVE_FORMAT_IBM_MULAW (0x0101) #define WAVE_FORMAT_IBM_ALAW (0x0102) #define WAVE_FORMAT_IBM_ADPCM (0x0103) #define WAVE_FORMAT_AC3 (0x2000) /*extra audio formats (codecs)*/ #define ANTEX_FORMAT_ADPCME (0x0033) #define AUDIO_FORMAT_APTX (0x0025) #define AUDIOFILE_FORMAT_AF10 (0x0026) #define AUDIOFILE_FORMAT_AF36 (0x0024) #define BROOKTREE_FORMAT_BTVD (0x0400) #define CANOPUS_FORMAT_ATRAC (0x0063) #define CIRRUS_FORMAT_CIRRUS (0x0060) #define CONTROL_FORMAT_CR10 (0x0037) #define CONTROL_FORMAT_VQLPC (0x0034) #define CREATIVE_FORMAT_ADPCM (0x0200) #define CREATIVE_FORMAT_FASTSPEECH10 (0x0203) #define CREATIVE_FORMAT_FASTSPEECH8 (0x0202) #define IMA_FORMAT_ADPCM (0x0039) #define CONSISTENT_FORMAT_CS2 (0x0260) #define HP_FORMAT_CU (0x0019) #define DEC_FORMAT_G723 (0x0123) #define DF_FORMAT_G726 (0x0085) #define DSP_FORMAT_ADPCM (0x0036) #define DOLBY_FORMAT_AC2 (0x0030) #define DOLBY_FORMAT_AC3_SPDIF (0x0092) #define ESS_FORMAT_ESPCM (0x0061) #define IEEE_FORMAT_FLOAT (0x0003) #define MS_FORMAT_MSAUDIO1_DIVX (0x0160) #define MS_FORMAT_MSAUDIO2_DIVX (0x0161) #define OGG_FORMAT_VORBIS (0x566f) #define OGG_FORMAT_VORBIS1 (0x674f) #define OGG_FORMAT_VORBIS1P (0x676f) #define OGG_FORMAT_VORBIS2 (0x6750) #define OGG_FORMAT_VORBIS2P (0x6770) #define OGG_FORMAT_VORBIS3 (0x6751) #define OGG_FORMAT_VORBIS3P (0x6771) #define MS_FORMAT_WMA9 (0x0163) #define MS_FORMAT_WMA9_PRO (0x0162) /*video buffer flags*/ #define VIDEO_BUFF_FREE (0) #define VIDEO_BUFF_USED (1) /* * set pause timestamp * args: * value - timestamp value * * asserts: * none * * returns: none */ void set_video_pause_timestamp(int64_t timestamp); /* * get pause timestamp * args: * value: nome * * asserts: * none * * returns: pause timestamp */ void /*__attribute__ ((constructor)) */gviewencoder_init(); int64_t get_video_pause_timestamp(void); /* * codec data struct used for encoder context * we set all avcodec stuff here so that we don't * need to export any of it's symbols in the public API */ typedef struct _encoder_codec_data_t { AVCodec *codec; AVDictionary *private_options; AVCodecContext *codec_context; AVFrame *frame; AVPacket *outpkt; } encoder_codec_data_t; typedef struct _bmp_info_header_t { uint32_t biSize; /*size of this header 40 bytes*/ int32_t biWidth; int32_t biHeight; uint16_t biPlanes; /*color planes - set to 1*/ uint16_t biBitCount; /*bits per pixel - color depth (use 24)*/ uint32_t biCompression; /*BI_RGB = 0*/ uint32_t biSizeImage; uint32_t biXPelsPerMeter; uint32_t biYPelsPerMeter; uint32_t biClrUsed; uint32_t biClrImportant; } __attribute__ ((packed)) bmp_info_header_t; /* * get default mkv_codecPriv * args: * none * * asserts: * none * * returns: pointer to bmp_info_header_t */ bmp_info_header_t *get_default_mkv_codecPriv(); /* * split xiph headers from libav private data * args: * extradata - libav codec private data * extradata_size - codec private data size * first_header_size - first header size * header_start - first 3 bytes of header * header_len - header length * * asserts: * none * * returns: error code */ int avpriv_split_xiph_headers( uint8_t *extradata, int extradata_size, int first_header_size, uint8_t *header_start[3], int header_len[3]); /* * set yu12 frame in codec data frame * args: * video_codec_data - pointer to video codec data * inp - input data (yu12) * width - frame width * height - frame height * * asserts: * video_codec_data is not null * inp is not null * * returns: none */ void prepare_video_frame(encoder_codec_data_t *encoder_ctx, uint8_t *inp, int width, int height); /* * returns the real codec array index * args: * codec_id - codec id * * asserts: * none * * returns: real index or -1 if none */ int get_video_codec_index(int codec_id); /* * returns the list codec index * args: * codec_id - codec id * * asserts: * none * * returns: list index or -1 if none */ int get_video_codec_list_index(int codec_id); /* * returns the real codec array index * args: * codec_id - codec id * * asserts: * none * * returns: real index or -1 if none */ int get_audio_codec_index(int codec_id); /* * returns the list codec index * args: * codec_id - codec id * * asserts: * none * * returns: real index or -1 if none */ int get_audio_codec_list_index(int codec_id); /* * get audio mkv codec * args: * codec_ind - codec list index * * asserts: * none * * returns: mkv codec entry or NULL if none */ const char *encoder_get_audio_mkv_codec(int codec_ind); /* * get video mkv codec * args: * codec_ind - codec list index * * asserts: * none * * returns: mkv codec entry or NULL if none */ const char *encoder_get_video_mkv_codec(int codec_ind); /* * get video compressor (avi 4cc code) * args: * codec_ind - codec list index * * asserts: * none * * returns: compressor codec entry or NULL if none */ const char *encoder_get_video_codec_4cc(int codec_ind); /* * get audio codec bits * args: * codec_ind - codec list index * * asserts: * none * * returns: bits entry from audio codec list */ int encoder_get_audio_bits(int codec_ind); /* * get audio codec bit rate * args: * codec_ind - codec list index * * asserts: * none * * returns: bit_rate entry from audio codec list */ int encoder_get_audio_bit_rate(int codec_ind); #endif
9,582
C
.c
307
28.785016
97
0.603569
linuxdeepin/dtkmultimedia
3
16
2
LGPL-3.0
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
15,285,519
muxer.c
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam_encoder/muxer.c
/*******************************************************************************# # guvcview http://guvcview.sourceforge.net # # # # Paulo Assis <[email protected]> # # Nobuhiro Iwamatsu <[email protected]> # # Add UYVY color support(Macbook iSight) # # Flemming Frandsen <[email protected]> # # Add VU meter OSD # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 2 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program; if not, write to the Free Software # # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # ********************************************************************************/ /*******************************************************************************# # # # Encoder library # # # ********************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <linux/videodev2.h> #include <string.h> //#include <errno.h> #include <assert.h> #include <sys/statfs.h> #include <libavformat/avformat.h> #include <libavutil/avassert.h> #include <libavutil/channel_layout.h> #include <libavutil/opt.h> #include <libavutil/frame.h> #include <libavutil/mathematics.h> #include <libavutil/timestamp.h> #include <libavutil/hwcontext.h> #include <libswscale/swscale.h> #include <libswresample/swresample.h> /* support for internationalization - i18n */ #include <locale.h> #include <libintl.h> #include "cameraconfig.h" #include "gviewencoder.h" #include "encoder.h" #include "stream_io.h" #include "matroska.h" #include "avi.h" #include "mp4.h" #include "gview.h" #include "load_libs.h" extern int verbosity; static mkv_context_t *mkv_ctx = NULL; static avi_context_t *avi_ctx = NULL; static AVFormatContext *mp4_ctx = NULL; static stream_io_t *video_stream = NULL; static stream_io_t *audio_stream = NULL; static OutputStream *mp4_video_stream = NULL; static OutputStream *mp4_audio_stream = NULL; //static AVCodec *audio_codec = NULL; //static AVCodec *video_codec = NULL; static AVDictionary** opt = NULL; /*file mutex*/ static __MUTEX_TYPE mutex = __STATIC_MUTEX_INIT; #define __PMUTEX &mutex /* * mux a video frame * args: * encoder_ctx - pointer to encoder context * * asserts: * encoder_ctx is not null; * * returns: error code */ int encoder_write_video_data(encoder_context_t *encoder_ctx) { /*assertions*/ assert(encoder_ctx); encoder_video_context_t *enc_video_ctx = encoder_ctx->enc_video_ctx; assert(enc_video_ctx); //cheese_print_log("encoder_write_video_data"); if(enc_video_ctx->outbuf_coded_size <= 0){ //cheese_print_log("enc_video_ctx->outbuf_coded_size <= 0"); return -1; } //else { //cheese_print_log("enc_video_ctx->outbuf_coded_size >= 0"); //} enc_video_ctx->framecount++; int ret =0; int block_align = 1; encoder_codec_data_t *video_codec_data = (encoder_codec_data_t *) enc_video_ctx->codec_data; if(video_codec_data) block_align = video_codec_data->codec_context->block_align; __LOCK_MUTEX( __PMUTEX ); switch (encoder_ctx->muxer_id) { case ENCODER_MUX_AVI: ret = avi_write_packet( avi_ctx, 0, enc_video_ctx->outbuf, (uint32_t)enc_video_ctx->outbuf_coded_size, enc_video_ctx->dts, block_align, enc_video_ctx->flags); break; case ENCODER_MUX_MP4: //cheese_print_log("write video data"); ret = mp4_write_packet(mp4_ctx, video_codec_data, 0, enc_video_ctx->outbuf, (uint32_t)enc_video_ctx->outbuf_coded_size, (uint64_t)enc_video_ctx->pts, enc_video_ctx->flags); break; case ENCODER_MUX_MKV: case ENCODER_MUX_WEBM: ret = mkv_write_packet( mkv_ctx, 0, enc_video_ctx->outbuf, enc_video_ctx->outbuf_coded_size, enc_video_ctx->duration, (uint64_t)enc_video_ctx->pts, enc_video_ctx->flags); break; default: break; } __UNLOCK_MUTEX( __PMUTEX ); return (ret); } /* * mux a audio frame * args: * encoder_ctx - pointer to encoder context * * asserts: * encoder_ctx is not null; * * returns: error code */ int encoder_write_audio_data(encoder_context_t *encoder_ctx) { /*assertions*/ assert(encoder_ctx != NULL); encoder_audio_context_t *enc_audio_ctx = encoder_ctx->enc_audio_ctx; if(!enc_audio_ctx || encoder_ctx->audio_channels <= 0) return -1; if(enc_audio_ctx->outbuf_coded_size <= 0) return -1; if(verbosity > 3) printf("ENCODER: writing %i bytes of audio data\n", enc_audio_ctx->outbuf_coded_size); int ret =0; int block_align = 1; encoder_codec_data_t *audio_codec_data = (encoder_codec_data_t *) enc_audio_ctx->codec_data; if(audio_codec_data) block_align = audio_codec_data->codec_context->block_align; __LOCK_MUTEX( __PMUTEX ); switch (encoder_ctx->muxer_id) { case ENCODER_MUX_AVI: ret = avi_write_packet( avi_ctx, 1, enc_audio_ctx->outbuf, (uint32_t)enc_audio_ctx->outbuf_coded_size, enc_audio_ctx->dts, block_align, enc_audio_ctx->flags); break; case ENCODER_MUX_MP4: // cheese_print_log("write audio data"); mp4_write_packet( mp4_ctx, audio_codec_data, 1, enc_audio_ctx->outbuf, (uint32_t)enc_audio_ctx->outbuf_coded_size, (uint64_t)enc_audio_ctx->pts, enc_audio_ctx->flags); break; case ENCODER_MUX_MKV: case ENCODER_MUX_WEBM: ret = mkv_write_packet( mkv_ctx, 1, enc_audio_ctx->outbuf, enc_audio_ctx->outbuf_coded_size, enc_audio_ctx->duration, (uint64_t)enc_audio_ctx->pts, enc_audio_ctx->flags); break; default: break; } __UNLOCK_MUTEX( __PMUTEX ); return (ret); } /* * initialization of the file muxer * args: * encoder_ctx - pointer to encoder context * filename - video filename * * asserts: * encoder_ctx is not null * encoder_ctx->enc_video_ctx is not null * * returns: none */ void encoder_muxer_init(encoder_context_t *encoder_ctx, const char *filename) { /*assertions*/ assert(encoder_ctx != NULL); assert(encoder_ctx->enc_video_ctx != NULL); encoder_codec_data_t *video_codec_data = (encoder_codec_data_t *) encoder_ctx->enc_video_ctx->codec_data; int video_codec_id = AV_CODEC_ID_NONE; if(encoder_ctx->video_codec_ind == 0) /*no codec_context*/ { switch(encoder_ctx->input_format) { case V4L2_PIX_FMT_H264: video_codec_id = AV_CODEC_ID_H264; break; } } else if(video_codec_data) { video_codec_id = (int)video_codec_data->codec_context->codec_id; } if(verbosity > 1) printf("ENCODER: initializing muxer(%i)\n", encoder_ctx->muxer_id); switch (encoder_ctx->muxer_id) { case ENCODER_MUX_AVI: if(avi_ctx != NULL) { avi_destroy_context(avi_ctx); avi_ctx = NULL; } avi_ctx = avi_create_context(filename); /*add video stream*/ video_stream = avi_add_video_stream( avi_ctx, encoder_ctx->video_width, encoder_ctx->video_height, encoder_ctx->fps_den, encoder_ctx->fps_num, video_codec_id); if(video_codec_id == AV_CODEC_ID_THEORA && video_codec_data) { video_stream->extra_data = (uint8_t *) video_codec_data->codec_context->extradata; video_stream->extra_data_size = video_codec_data->codec_context->extradata_size; } /*add audio stream*/ if(encoder_ctx->enc_audio_ctx != NULL && encoder_ctx->audio_channels > 0) { encoder_codec_data_t *audio_codec_data = (encoder_codec_data_t *) encoder_ctx->enc_audio_ctx->codec_data; if(audio_codec_data) { int acodec_ind = get_audio_codec_list_index((int)audio_codec_data->codec_context->codec_id); /*sample size - only used for PCM*/ int32_t a_bits = encoder_get_audio_bits(acodec_ind); /*bit rate (compressed formats)*/ int32_t b_rate = encoder_get_audio_bit_rate(acodec_ind); audio_stream = avi_add_audio_stream( avi_ctx, encoder_ctx->audio_channels, encoder_ctx->audio_samprate, a_bits, b_rate, (int32_t)audio_codec_data->codec_context->codec_id, encoder_ctx->enc_audio_ctx->avi_4cc); if(audio_codec_data->codec_context->codec_id == AV_CODEC_ID_VORBIS) { audio_stream->extra_data = (uint8_t *) audio_codec_data->codec_context->extradata; audio_stream->extra_data_size = audio_codec_data->codec_context->extradata_size; } } } /* add first riff header */ avi_add_new_riff(avi_ctx); break; case ENCODER_MUX_MP4: //av_register_all(); if(mp4_ctx != NULL) { mp4_destroy_context(mp4_ctx); mp4_ctx = NULL; } mp4_ctx = mp4_create_context(filename); mp4_video_stream = (OutputStream*)calloc(1,sizeof(OutputStream)); mp4_add_video_stream( mp4_ctx, video_codec_data, mp4_video_stream); int ret = getLoadLibsInstance()->m_avcodec_parameters_from_context(mp4_video_stream->st->codecpar, mp4_video_stream->enc); if (ret < 0) { fprintf(stderr, "Could not copy the stream parameters\n"); exit(1); } if(encoder_ctx->enc_audio_ctx != NULL && encoder_ctx->audio_channels > 0) { encoder_codec_data_t *audio_codec_data = (encoder_codec_data_t *) encoder_ctx->enc_audio_ctx->codec_data; if(audio_codec_data) { mp4_audio_stream = (OutputStream*)calloc(1,sizeof(OutputStream)); mp4_add_audio_stream( mp4_ctx, audio_codec_data, mp4_audio_stream); } if(!video_codec_data->private_options) getAvutil()->m_av_dict_copy(opt,video_codec_data->private_options, AV_DICT_DONT_OVERWRITE); int ret = getLoadLibsInstance()->m_avcodec_parameters_from_context(mp4_audio_stream->st->codecpar, mp4_audio_stream->enc); if (ret < 0) { fprintf(stderr, "Could not copy the stream parameters\n"); exit(1); } //if(!audio_codec_data->private_options) //av_dict_copy(opt,video_codec_data->private_options, AV_DICT_DONT_OVERWRITE); } ret = getAvformat()->m_avio_open(&mp4_ctx->pb, filename, AVIO_FLAG_WRITE); if (ret < 0) { //fprintf(stderr, "Could not open '%s': %s\n", filename, //av_err2str(ret)); } ret= getAvformat()->m_avformat_write_header(mp4_ctx, opt); if(ret < 0) { // fprintf(stderr, "Error occurred when opening output file: %s\n", // av_err2str(ret)); } break; default: case ENCODER_MUX_MKV: case ENCODER_MUX_WEBM: if(mkv_ctx != NULL) { mkv_destroy_context(mkv_ctx); mkv_ctx = NULL; } mkv_ctx = mkv_create_context(filename, encoder_ctx->muxer_id); /*add video stream*/ video_stream = mkv_add_video_stream( mkv_ctx, encoder_ctx->video_width, encoder_ctx->video_height, encoder_ctx->fps_den, encoder_ctx->fps_num, video_codec_id); video_stream->extra_data_size = encoder_set_video_mkvCodecPriv(encoder_ctx); if(video_stream->extra_data_size > 0) { video_stream->extra_data = (uint8_t *) encoder_get_video_mkvCodecPriv(encoder_ctx->video_codec_ind); if(encoder_ctx->input_format == V4L2_PIX_FMT_H264) video_stream->h264_process = 1; //we need to process NALU marker } /*add audio stream*/ if(encoder_ctx->enc_audio_ctx != NULL && encoder_ctx->audio_channels > 0) { encoder_codec_data_t *audio_codec_data = (encoder_codec_data_t *) encoder_ctx->enc_audio_ctx->codec_data; if(audio_codec_data) { mkv_ctx->audio_frame_size = audio_codec_data->codec_context->frame_size; /*sample size - only used for PCM*/ int32_t a_bits = encoder_get_audio_bits(encoder_ctx->audio_codec_ind); /*bit rate (compressed formats)*/ int32_t b_rate = encoder_get_audio_bit_rate(encoder_ctx->audio_codec_ind); audio_stream = mkv_add_audio_stream( mkv_ctx, encoder_ctx->audio_channels, encoder_ctx->audio_samprate, a_bits, b_rate, (int32_t)audio_codec_data->codec_context->codec_id, encoder_ctx->enc_audio_ctx->avi_4cc); audio_stream->extra_data_size = encoder_set_audio_mkvCodecPriv(encoder_ctx); if(audio_stream->extra_data_size > 0) audio_stream->extra_data = encoder_get_audio_mkvCodecPriv(encoder_ctx->audio_codec_ind); } } /* write the file header */ mkv_write_header(mkv_ctx); break; } } /* * close the file muxer * args: * encoder_ctx - pointer to encoder context * * asserts: * none * * returns: none */ void encoder_muxer_close(encoder_context_t *encoder_ctx) { switch (encoder_ctx->muxer_id) { case ENCODER_MUX_AVI: if (avi_ctx) { /*last frame pts*/ float tottime = (float) ((int64_t) (encoder_ctx->enc_video_ctx->pts) / 1000000); // convert to miliseconds if (verbosity > 0) printf("ENCODER: (avi) time = %f\n", (double)tottime); if (tottime > 0) { /*try to find the real frame rate*/ avi_ctx->fps = (double) (encoder_ctx->enc_video_ctx->framecount * 1000) / (double)tottime; } if (verbosity > 0) printf("ENCODER: (avi) %"PRId64" frames in %f ms [ %f fps]\n", encoder_ctx->enc_video_ctx->framecount, (double)tottime, avi_ctx->fps); //close sound ?? avi_close(avi_ctx); avi_destroy_context(avi_ctx); avi_ctx = NULL; } break; case ENCODER_MUX_MP4: if(mp4_ctx) { getAvformat()->m_av_write_trailer(mp4_ctx); getAvformat()->m_avio_closep(&mp4_ctx->pb); // if(!!mp4_video_stream->enc) // avcodec_free_context(&mp4_video_stream->enc); if(!!mp4_video_stream->frame) getAvutil()->m_av_frame_free(&mp4_video_stream->frame); if(!!mp4_video_stream->tmp_frame) getAvutil()->m_av_frame_free(&mp4_video_stream->tmp_frame); if(!!mp4_video_stream->sws_ctx) getLoadLibsInstance()->m_sws_freeContext(mp4_video_stream->sws_ctx); if(!!mp4_video_stream->swr_ctx) getLoadLibsInstance()->m_swr_free(&mp4_video_stream->swr_ctx); if(!!mp4_video_stream) { free(mp4_video_stream); mp4_video_stream = NULL; } //if(!!mp4_audio_stream->enc) //avcodec_free_context(&mp4_audio_stream->enc); if(!!mp4_audio_stream->frame) getAvutil()->m_av_frame_free(&mp4_audio_stream->frame); if(!!mp4_audio_stream->tmp_frame) getAvutil()->m_av_frame_free(&mp4_audio_stream->tmp_frame); if(!!mp4_audio_stream->sws_ctx) getLoadLibsInstance()->m_sws_freeContext(mp4_audio_stream->sws_ctx); if(!!mp4_audio_stream->swr_ctx) getLoadLibsInstance()->m_swr_free(&mp4_audio_stream->swr_ctx); if(!!mp4_audio_stream) { free(mp4_audio_stream); mp4_audio_stream = NULL; } mp4_destroy_context(mp4_ctx); mp4_ctx = NULL; //malloc_trim(0); } break; default: case ENCODER_MUX_MKV: case ENCODER_MUX_WEBM: if(mkv_ctx != NULL) { mkv_close(mkv_ctx); mkv_destroy_context(mkv_ctx); mkv_ctx = NULL; } break; } } /* * function to determine if enought free space is available * args: * treshold: limit treshold in Kbytes (min. free space) * * asserts: * none * * returns: 1 if still enough free space left on disk * 0 otherwise */ int encoder_disk_supervisor(int treshold, const char *path) { /* * treshold: * 51200 = 50Mb * 102400 = 100Mb * 358400 = 300Mb * 512000 = 500Mb */ int percent = 0; uint64_t free_kbytes=0; uint64_t total_kbytes=0; struct statfs buf; statfs(path, &buf); total_kbytes= buf.f_blocks * (__fsblkcnt_t)(buf.f_bsize/1024); free_kbytes= buf.f_bavail * (__fsblkcnt_t)(buf.f_bsize/1024); if(total_kbytes > 0) percent = (int) ((1.0f-((float)free_kbytes/(float)total_kbytes))*100.0f); else { fprintf(stderr, "ENCODER: couldn't get disk stats for %s\n", path); return (0); /* don't invalidate video capture*/ } if(verbosity > 0) printf("ENCODER: (%s) %lluK bytes free on a total of %lluK (used: %d %%) treshold=%iK\n", path, (unsigned long long) free_kbytes, (unsigned long long) total_kbytes, percent, treshold); if(free_kbytes < (uint64_t)treshold) { fprintf(stderr,"ENCODER: Not enough free disk space (%lluKb) left on disk, need > %ik \n", (unsigned long long) free_kbytes, treshold); return(0); /* not enough free space left on disk */ } return (1); /* still have enough free space on disk */ }
19,337
C
.c
537
29.35568
139
0.563679
linuxdeepin/dtkmultimedia
3
16
2
LGPL-3.0
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
15,285,524
mp4.c
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam_encoder/mp4.c
// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: LGPL-3.0-or-later #include "mp4.h" #include <libavutil/mathematics.h> #include "load_libs.h" static int64_t video_pts = 0; static int64_t audio_pts = 0; static int64_t first_pts = 0; static int64_t last_pts = 0; AVFormatContext *mp4_create_context(const char *filename) { AVFormatContext *mp4_ctx; getAvformat()->m_avformat_alloc_output_context2(&mp4_ctx, NULL, NULL, filename); if (!mp4_ctx) { printf("Could not deduce output format from file extension: using MPEG.\n"); getAvformat()->m_avformat_alloc_output_context2(&mp4_ctx, NULL, "mpeg", filename); } if (!mp4_ctx) { fprintf(stderr, "ENCODER: FATAL memory allocation failure (mp4_create_context): %s\n", strerror(errno)); exit(-1); } return mp4_ctx; } void mp4_add_video_stream( AVFormatContext *mp4_ctx, encoder_codec_data_t *video_codec_data, OutputStream *video_stream) { video_stream->st = getAvformat()->m_avformat_new_stream(mp4_ctx, video_codec_data->codec); if(!video_stream->st) { fprintf(stderr,"Could not allocate stream\n"); exit(1); } video_stream->st->id = mp4_ctx->nb_streams - 1; video_stream->enc = video_codec_data->codec_context; video_stream->st->time_base = video_codec_data->codec_context->time_base; if(mp4_ctx->oformat->flags & AVFMT_GLOBALHEADER) { video_stream->enc->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; } } void mp4_add_audio_stream( AVFormatContext *mp4_ctx, encoder_codec_data_t *audio_codec_data, OutputStream *audio_stream) { audio_stream->st = getAvformat()->m_avformat_new_stream(mp4_ctx,audio_codec_data->codec); if(!audio_stream->st) { fprintf(stderr,"Could not allocate stream\n"); exit(1); } audio_stream->st->id = mp4_ctx->nb_streams - 1; audio_stream->st->time_base = audio_codec_data->codec_context->time_base; audio_stream->enc = audio_codec_data->codec_context; if(mp4_ctx->oformat->flags & AVFMT_GLOBALHEADER) { audio_stream->enc->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; } } int mp4_write_packet( AVFormatContext *mp4_ctx, encoder_codec_data_t *codec_data, int stream_index, uint8_t *outbuf, uint32_t outbuf_size, uint64_t pts, int flags) { AVPacket *outpacket = codec_data->outpkt; outpacket->data = (uint8_t*)calloc((unsigned int)outbuf_size, sizeof(uint8_t)); memcpy(outpacket->data, outbuf, outbuf_size); outpacket->size =(int)outbuf_size; if(codec_data->codec_context->codec_type == AVMEDIA_TYPE_VIDEO){ outpacket->pts = video_pts; outpacket->dts = video_pts; outpacket->duration = 0; outpacket->flags = flags; outpacket->stream_index = stream_index; AVRational video_time = mp4_ctx->streams[stream_index]->time_base; AVRational time_base = codec_data->codec_context->time_base; if (video_pts > last_pts || video_pts == 0) { getLoadLibsInstance()->m_av_packet_rescale_ts(outpacket, time_base, video_time); getAvformat()->m_av_write_frame(mp4_ctx, outpacket); set_video_time_capture((double)(pts)/1000/1000000); } else { fprintf(stderr,"pts err:video_pts: %d last_pts: %d\n", video_pts, last_pts); } last_pts = video_pts; if (first_pts == 0) { first_pts = pts; } else { video_pts = (double)(pts - first_pts) / 1000000.0 / 33.0; if (video_pts == last_pts) //pts must be strictly incremented video_pts++; if(video_pts < last_pts) video_pts = last_pts + 1; } } if(codec_data->codec_context->codec_type == AVMEDIA_TYPE_AUDIO) { outpacket->pts = audio_pts; outpacket->flags = flags; outpacket->stream_index = stream_index; AVRational audio_time = mp4_ctx->streams[stream_index]->time_base; AVRational time_base = codec_data->codec_context->time_base; getLoadLibsInstance()->m_av_packet_rescale_ts(outpacket, time_base, audio_time); getAvformat()->m_av_write_frame(mp4_ctx, outpacket); //AAC音频标准是1024 //MP3音频标准是1152 audio_pts+= 1024; } if(outpacket->data){ free(outpacket->data); outpacket->data = NULL; getLoadLibsInstance()->m_av_packet_unref(outpacket); } return 0; } void mp4_destroy_context(AVFormatContext *mp4_ctx) { video_pts = 0; audio_pts = 0; first_pts = 0; if(mp4_ctx != NULL) { getAvformat()->m_avformat_free_context(mp4_ctx); //mp4_ctx = NULL; } }
4,807
C
.c
132
29.780303
106
0.634183
linuxdeepin/dtkmultimedia
3
16
2
LGPL-3.0
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,285,527
render.c
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam_render/render.c
/*******************************************************************************# # guvcview http://guvcview.sourceforge.net # # # # Paulo Assis <[email protected]> # # Nobuhiro Iwamatsu <[email protected]> # # Add UYVY color support(Macbook iSight) # # Flemming Frandsen <[email protected]> # # Add VU meter OSD # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 2 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program; if not, write to the Free Software # # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # ********************************************************************************/ /*******************************************************************************# # # # Render library # # # ********************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <errno.h> #include <assert.h> /* support for internationalization - i18n */ #include <locale.h> #include <libintl.h> #include "gviewrender.h" #include "render.h" #include "cameraconfig.h" //#if ENABLE_SDL2 // #include "render_sdl2.h" //#endif extern int verbosity; static int render_api = RENDER_SDL; static int my_width = 0; static int my_height = 0; static uint32_t my_osd_mask = REND_OSD_NONE; static uint32_t my_crosshair_color_rgb = 0x0000FF00; static float osd_vu_level[2] = {0, 0}; static render_events_t render_events_list[] = { { .id = EV_QUIT, .callback = NULL, .data = NULL }, { .id = EV_KEY_UP, .callback = NULL, .data = NULL }, { .id = EV_KEY_DOWN, .callback = NULL, .data = NULL }, { .id = EV_KEY_LEFT, .callback = NULL, .data = NULL }, { .id = EV_KEY_RIGHT, .callback = NULL, .data = NULL }, { .id = EV_KEY_SPACE, .callback = NULL, .data = NULL }, { .id = EV_KEY_I, .callback = NULL, .data = NULL }, { .id = EV_KEY_V, .callback = NULL, .data = NULL }, { .id = -1, /*end of list*/ .callback = NULL, .data = NULL } }; /* * set verbosity * args: * value - verbosity value * * asserts: * none * * returns: none */ void render_set_verbosity(int value) { verbosity = value; } /* * set the osd mask * args: * mask - osd mask (ored) * * asserts: * none * * returns: none */ void render_set_osd_mask(uint32_t mask) { my_osd_mask = mask; } /* * set the osd crosshair color * args: * rgb_color - 0x00RRGGBB * * asserts: * none * * returns: none */ void render_set_crosshair_color(uint32_t rgb_color) { my_crosshair_color_rgb = rgb_color; } /* * get the osd mask * args: * none * * asserts: * none * * returns: osd mask */ uint32_t render_get_osd_mask() { return (my_osd_mask); } /* * get the osd crosshair color * args: * none * * asserts: * none * * returns: osd rgb color */ uint32_t render_get_crosshair_color() { return (my_crosshair_color_rgb); } /* * set the vu level for the osd vu meter * args: * vu_level - vu level value (2 channel array) * * asserts: * none * * returns: none */ void render_set_vu_level(float vu_level[2]) { osd_vu_level[0] = vu_level[0]; osd_vu_level[1] = vu_level[1]; } /* * get the vu level for the osd vu meter * args: * vu_level - two channel array were vu_level is to be copied * * asserts: * none * * returns array with vu meter level */ void render_get_vu_level(float vu_level[2]) { vu_level[0] = osd_vu_level[0]; vu_level[1] = osd_vu_level[1]; } /* * get render width * args: * none * * asserts: * none * * returns: render width */ int render_get_width() { return my_width; } /* * get render height * args: * none * * asserts: * none * * returns: render height */ int render_get_height() { return my_height; } /* * render initialization * args: * render - render API to use (RENDER_NONE, RENDER_SDL1, ...) * width - render width * height - render height * flags - window flags: * 0- none * 1- fullscreen * 2- maximized * win_w - window width (0 use render width) * win_h - window height (0 use render height) * * asserts: * none * * returns: error code */ int render_init(int render, int width, int height, int flags, int win_w, int win_h) { int ret = 0; render_api = render; my_width = width; my_height = height; switch(render_api) { case RENDER_NONE: break; // #if ENABLE_SDL2 // case RENDER_SDL: // ret = init_render_sdl2(my_width, my_height, flags, win_w, win_h); // break; // #endif default: render_api = RENDER_NONE; break; } if(ret) render_api = RENDER_NONE; return ret; } /* * Apply fx filters * args: * frame - pointer to frame buffer (yu12 format) * mask - or'ed filter mask * * asserts: * frame is not null * * returns: void */ void render_frame_fx(uint8_t *frame, uint32_t mask) { /*asserts*/ assert(frame != NULL); render_fx_apply(frame, my_width, my_height, mask); } /* * Apply OSD mask * args: * frame - pointer to frame buffer (yu12 format) * * asserts: * frame is not null * * returns: void */ void render_frame_osd(uint8_t *frame) { float vu_level[2]; render_get_vu_level(vu_level); /*osd vu meter*/ if(((render_get_osd_mask() & (REND_OSD_VUMETER_MONO | REND_OSD_VUMETER_STEREO))) != 0) render_osd_vu_meter(frame, my_width, my_height, vu_level); /*osd crosshair*/ if(((render_get_osd_mask() & REND_OSD_CROSSHAIR)) != 0) render_osd_crosshair(frame, my_width, my_height); } /* * render a frame * args: * frame - pointer to frame data (yu12 format) * * asserts: * frame is not null * * returns: error code */ int render_frame(uint8_t *frame) { /*asserts*/ assert(frame != NULL); int ret = 0; switch(render_api) { case RENDER_NONE: break; // #if ENABLE_SDL2 // case RENDER_SDL: // ret = render_sdl2_frame(frame, my_width, my_height); // render_sdl2_dispatch_events(); // break; // #endif default: break; } return ret; } /* * set caption * args: * caption - string with render window caption * * asserts: * none * * returns: none */ void render_set_caption(const char* caption) { switch(render_api) { case RENDER_NONE: break; // #if ENABLE_SDL2 // case RENDER_SDL: // set_render_sdl2_caption(caption); // break; // #endif default: break; } } /* * clean render data * args: * none * * asserts: * none * * returns: none */ void render_close() { switch(render_api) { case RENDER_NONE: break; // #if ENABLE_SDL2 // case RENDER_SDL: // render_sdl2_clean(); // break; // #endif default: break; } /*clean fx data*/ render_clean_fx(); my_width = 0; my_height = 0; } /* * get event index on render_events_list * args: * id - event id * * asserts: * none * * returns: event index or -1 on error */ int render_get_event_index(int id) { int i = 0; while(render_events_list[i].id >= 0) { if(render_events_list[i].id == id) return i; i++; } return -1; } /* * set event callback * args: * id - event id * callback_function - pointer to callback function * data - pointer to user data (passed to callback) * * asserts: * none * * returns: error code */ int render_set_event_callback(int id, render_event_callback callback_function, void *data) { int index = render_get_event_index(id); if(index < 0) return index; render_events_list[index].callback = callback_function; render_events_list[index].data = data; return 0; } /* * call the event callback for event id * args: * id - event id * * asserts: * none * * returns: error code */ int render_call_event_callback(int id) { int index = render_get_event_index(id); if(verbosity > 1) printf("RENDER: event %i -> callback %i\n", id, index); if(index < 0) return index; if(render_events_list[index].callback == NULL) return -1; int ret = render_events_list[index].callback(render_events_list[index].data); return ret; }
9,621
C
.c
457
19.111597
90
0.559679
linuxdeepin/dtkmultimedia
3
16
2
LGPL-3.0
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
15,285,529
render_fx.c
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam_render/render_fx.c
/*******************************************************************************# # guvcview http://guvcview.sourceforge.net # # # # Paulo Assis <[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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # ********************************************************************************/ #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <inttypes.h> #include <unistd.h> #include <assert.h> #include <math.h> #include <time.h> #include "gviewrender.h" #include "gview.h" #include "cameraconfig.h" /*random generator (HAS_GSL is set in ../config.h)*/ #ifdef HAS_GSL #include <gsl/gsl_rng.h> #endif typedef struct _blur_t { int n; //number of iterations int sigma; //deviation int* bSizes; //box sizes array int** divTable; //division lookup table for each box size } blur_t; static blur_t* blur[2] = {NULL, NULL}; //LMH0612下方变量改为static static uint8_t *tmpbuffer = NULL; static uint32_t *TB_Sqrt_ind = NULL; //look up table for sqrt lens distort indexes static uint32_t *TB_Pow_ind = NULL; //look up table for pow lens distort indexes static uint32_t *TB_Pow2_ind = NULL; //look up table for pow2 lens distort indexes // uint8_t *tmpbuffer = NULL; // uint32_t *TB_Sqrt_ind = NULL; //look up table for sqrt lens distort indexes // uint32_t *TB_Pow_ind = NULL; //look up table for pow lens distort indexes // uint32_t *TB_Pow2_ind = NULL; //look up table for pow2 lens distort indexes typedef struct _particle_t { int PX; int PY; uint8_t Y; uint8_t U; uint8_t V; int size; float decay; } particle_t; static particle_t* particles = NULL; /* * Flip yu12 frame - horizontal * args: * frame - pointer to frame buffer (yu12=iyuv format) * width - frame width * height- frame height * * asserts: * frame is not null * * returns: void */ static void fx_yu12_mirror (uint8_t *frame, int width, int height) { /*asserts*/ assert(frame != NULL); int h=0; int w=0; //LMH消除警告 // int y_sizeline = width; // int c_sizeline = width/2; uint8_t *end = NULL; uint8_t *end2 = NULL; uint8_t *py = frame; uint8_t *pu = frame + (width * height); uint8_t *pv = pu + ((width * height) / 4); uint8_t pixel =0; uint8_t pixel2=0; /*mirror y*/ for(h = 0; h < height; h++) { py = frame + (h * width); end = py + width - 1; for(w = 0; w < width/2; w++) { pixel = *py; *py++ = *end; *end-- = pixel; } } /*mirror u v*/ for(h = 0; h < height; h+=2) { pu = frame + (width * height) + ((h * width) / 4); pv = pu + ((width * height) / 4); end = pu + (width / 2) - 1; end2 = pv + (width / 2) -1; for(w = 0; w < width/2; w+=2) { pixel = *pu; pixel2 = *pv; *pu++ = *end; *pv++ = *end2; *end-- = pixel; *end2-- = pixel2; } } } /* * Flip half yu12 frame - horizontal * args: * frame - pointer to frame buffer (yu12=iyuv format) * width - frame width * height- frame height * * asserts: * frame is not null * * returns: void */ static void fx_yu12_half_mirror (uint8_t *frame, int width, int height) { /*asserts*/ assert(frame != NULL); int h=0; int w=0; uint8_t *end = NULL; uint8_t *end2 = NULL; uint8_t *py = frame; uint8_t *pu = frame + (width * height); uint8_t *pv = pu + ((width * height) / 4); //LMH消除警告 // uint8_t pixel =0; // uint8_t pixel2=0; /*mirror y*/ for(h = 0; h < height; h++) { py = frame + (h * width); end = py + width - 1; for(w = 0; w < width/2; w++) { *end-- = *py++; } } /*mirror u v*/ for(h = 0; h < height; h+=2) { pu = frame + (width * height) + ((h * width) / 4); pv = pu + ((width * height) / 4); end = pu + (width / 2) - 1; end2 = pv + (width / 2) -1; for(w = 0; w < width/2; w+=2) { *end-- = *pu++; *end2-- = *pv++; } } } /* * Invert YUV frame * args: * frame - pointer to frame buffer (any yuv format) * width - frame width * height- frame height * * asserts: * frame is not null * * returns: void */ static void fx_yuv_negative(uint8_t *frame, int width, int height) { /*asserts*/ assert(frame != NULL); int size = (width * height * 5) / 4; int i=0; for(i=0; i < size; i++) frame[i] = ~frame[i]; } /* * Flip yu12 frame - vertical * args: * frame - pointer to frame buffer (yu12 format) * width - frame width * height- frame height * * asserts: * frame is not null * * returns: void */ static void fx_yu12_upturn(uint8_t *frame, int width, int height) { /*asserts*/ assert(frame != NULL); int h = 0; uint8_t line[width]; /*line1 buffer*/ uint8_t *pi = frame; //begin of first y line uint8_t *pf = pi + (width * (height - 1)); //begin of last y line /*upturn y*/ for ( h = 0; h < height / 2; ++h) { /*line iterator*/ memcpy(line, pi,(size_t) width); memcpy(pi, pf, (size_t)width); memcpy(pf, line, (size_t)width); pi+=width; pf-=width; } /*upturn u*/ pi = frame + (width * height); //begin of first u line pf = pi + ((width * height) / 4) - (width / 2); //begin of last u line for ( h = 0; h < height / 2; h += 2) //every two lines = height / 4 { /*line iterator*/ memcpy(line, pi, (size_t)width / 2); memcpy(pi, pf, (size_t)width / 2); memcpy(pf, line,(size_t) width / 2); pi+=width/2; pf-=width/2; } /*upturn v*/ pi = frame + ((width * height * 5) / 4); //begin of first v line pf = pi + ((width * height) / 4) - (width / 2); //begin of last v line for ( h = 0; h < height / 2; h += 2) //every two lines = height / 4 { /*line iterator*/ memcpy(line, pi, (size_t)width / 2); memcpy(pi, pf, (size_t)width / 2); memcpy(pf, line, (size_t)width / 2); pi+=width/2; pf-=width/2; } } /* * Flip half yu12 frame - vertical * args: * frame - pointer to frame buffer (yu12 format) * width - frame width * height- frame height * * asserts: * frame is not null * * returns: void */ static void fx_yu12_half_upturn(uint8_t *frame, int width, int height) { /*asserts*/ assert(frame != NULL); int h = 0; uint8_t line[width]; /*line1 buffer*/ uint8_t *pi = frame; //begin of first y line uint8_t *pf = pi + (width * (height - 1)); //begin of last y line /*upturn y*/ for ( h = 0; h < height / 2; ++h) { /*line iterator*/ memcpy(line, pi, (size_t)width); memcpy(pf, line, (size_t)width); pi+=width; pf-=width; } /*upturn u*/ pi = frame + (width * height); //begin of first u line pf = pi + ((width * height) / 4) - (width / 2); //begin of last u line for ( h = 0; h < height / 2; h += 2) //every two lines = height / 4 { /*line iterator*/ memcpy(line, pi, (size_t)width / 2); memcpy(pf, line, (size_t)width / 2); pi+=width/2; pf-=width/2; } /*upturn v*/ pi = frame + ((width * height * 5) / 4); //begin of first v line pf = pi + ((width * height) / 4) - (width / 2); //begin of last v line for ( h = 0; h < height / 2; h += 2) //every two lines = height / 4 { /*line iterator*/ memcpy(line, pi, (size_t)width / 2); memcpy(pf, line, (size_t)width / 2); pi+=width/2; pf-=width/2; } } /* * Monochromatic effect for yu12 frame * args: * frame - pointer to frame buffer (yu12 format) * width - frame width * height- frame height * * asserts: * frame is not null * * returns: void */ static void fx_yu12_monochrome(uint8_t* frame, int width, int height) { uint8_t *puv = frame + (width * height); //skip luma int i = 0; for(i=0; i < (width * height) / 2; ++i) { /* keep Y - luma */ *puv++=0x80;/*median (half the max value)=128*/ } } #ifdef HAS_GSL /* * Break yu12 image in little square pieces * args: * frame - pointer to frame buffer (yu12 format) * width - frame width * height - frame height * piece_size - multiple of 2 (we need at least 2 pixels to get the entire pixel information) * * asserts: * frame is not null */ static void fx_yu12_pieces(uint8_t* frame, int width, int height, int piece_size ) { int numx = width / piece_size; //number of pieces in x axis int numy = height / piece_size; //number of pieces in y axis uint8_t piece[(piece_size * piece_size * 3) / 2]; uint8_t *ppiece = piece; int i = 0, j = 0, w = 0, h = 0; /*random generator setup*/ gsl_rng_env_setup(); const gsl_rng_type *T = gsl_rng_default; gsl_rng *r = gsl_rng_alloc (T); int rot = 0; uint8_t *py = NULL; uint8_t *pu = NULL; uint8_t *pv = NULL; for(h = 0; h < height; h += piece_size) { for(w = 0; w < width; w += piece_size) { uint8_t *ppy = piece; uint8_t *ppu = piece + (piece_size * piece_size); uint8_t *ppv = ppu + ((piece_size * piece_size) / 4); for(i = 0; i < piece_size; ++i) { py = frame + ((h + i) * width) + w; for (j=0; j < piece_size; ++j) { *ppy++ = *py++; } } for(i = 0; i < piece_size; i += 2) { uint8_t *pu = frame + (width * height) + (((h + i) * width) / 4) + (w / 2); uint8_t *pv = pu + ((width * height) / 4); for(j = 0; j < piece_size; j += 2) { *ppu++ = *pu++; *ppv++ = *pv++; } } // ppy = piece; // ppu = piece + (piece_size * piece_size); // ppv = ppu + ((piece_size * piece_size) / 4); /*rotate piece and copy it to frame*/ //rotation is random rot = (int) lround(8 * gsl_rng_uniform (r)); /*0 to 8*/ switch(rot) { case 0: // do nothing break; case 5: case 1: //mirror fx_yu12_mirror(piece, piece_size, piece_size); break; case 6: case 2: //upturn fx_yu12_upturn(piece, piece_size, piece_size); break; case 4: case 3://mirror upturn fx_yu12_upturn(piece, piece_size, piece_size); fx_yu12_mirror(piece, piece_size, piece_size); break; default: //do nothing break; } ppy = piece; ppu = piece + (piece_size * piece_size); ppv = ppu + ((piece_size * piece_size) / 4); for(i = 0; i < piece_size; ++i) { py = frame + ((h + i) * width) + w; for (j=0; j < piece_size; ++j) { *py++ = *ppy++; } } for(i = 0; i < piece_size; i += 2) { uint8_t *pu = frame + (width * height) + (((h + i) * width) / 4) + (w / 2); uint8_t *pv = pu + ((width * height) / 4); for(j = 0; j < piece_size; j += 2) { *pu++ = *ppu++; *pv++ = *ppv++; } } } } /*free the random seed generator*/ gsl_rng_free (r); } /* * Trail of particles obtained from the image frame * args: * frame - pointer to frame buffer (yu12 format) * width - frame width * height - frame height * trail_size - trail size (in frames) * particle_size - maximum size in pixels - should be even (square - size x size) * * asserts: * frame is not null * * returns: void */ static void fx_particles(uint8_t* frame, int width, int height, int trail_size, int particle_size) { /*asserts*/ assert(frame != NULL); int i,j,w,h = 0; int part_w = width>>7; int part_h = height>>6; /*random generator setup*/ gsl_rng_env_setup(); const gsl_rng_type *T = gsl_rng_default; gsl_rng *r = gsl_rng_alloc (T); /*allocation*/ if (particles == NULL) { particles = calloc(trail_size * part_w * part_h, sizeof(particle_t)); if(particles == NULL) { fprintf(stderr,"RENDER: FATAL memory allocation failure (fx_particles): %s\n", strerror(errno)); exit(-1); } } particle_t *part = particles; particle_t *part1 = part; /*move particles in trail*/ for (i = trail_size; i > 1; --i) { part += (i - 1) * part_w * part_h; part1 += (i - 2) * part_w * part_h; for (j= 0; j < part_w * part_h; ++j) { if(part1->decay > 0) { part->PX = part1->PX + (int) lround(3 * gsl_rng_uniform (r)); /*0 to 3*/ part->PY = part1->PY -4 + (int) lround(5 * gsl_rng_uniform (r));/*-4 to 1*/ if(ODD(part->PX)) part->PX++; /*make sure PX is allways even*/ if((part->PX > (width-particle_size)) || (part->PY > (height-particle_size)) || (part->PX < 0) || (part->PY < 0)) { part->PX = 0; part->PY = 0; part->decay = 0; } else { part->decay = part1->decay - 1; } part->Y = part1->Y; part->U = part1->U; part->V = part1->V; part->size = part1->size; } else { part->decay = 0; } part++; part1++; } part = particles; /*reset*/ part1 = part; } part = particles; /*reset*/ /*get particles from frame (one pixel per particle - make PX allways even)*/ for(i =0; i < part_w * part_h; i++) { /* (2 * particle_size) to (width - 4 * particle_size)*/ part->PX = 2 * particle_size + (int) lround( (width - 6 * particle_size) * gsl_rng_uniform (r)); /* (2 * particle_size) to (height - 4 * particle_size)*/ part->PY = 2 * particle_size + (int) lround( (height - 6 * particle_size) * gsl_rng_uniform (r)); if(ODD(part->PX)) part->PX++; int y_pos = part->PX + (part->PY * width); int u_pos = (part->PX + (part->PY * width / 2)) / 2; int v_pos = u_pos + ((width * height) / 4); part->Y = frame[y_pos]; part->U = frame[u_pos]; part->V = frame[v_pos]; part->size = 1 + (int) lround((particle_size -1) * gsl_rng_uniform (r)); if(ODD(part->size)) part->size++; part->decay = (float) trail_size; part++; /*next particle*/ } part = particles; /*reset*/ int line = 0; float blend =0; float blend1 =0; /*render particles to frame (expand pixel to particle size)*/ for (i = 0; i < trail_size * part_w * part_h; i++) { if(part->decay > 0) { int y_pos = part->PX + (part->PY * width); int u_pos = (part->PX + (part->PY * width / 2)) / 2; int v_pos = u_pos + ((width * height) / 4); blend = part->decay/trail_size; blend1= 1 - blend; //y for(h = 0; h <(part->size); h++) { line = h * width; for (w = 0; w <(part->size); w++) { frame[y_pos + line + w] = CLIP((part->Y * blend) + (frame[y_pos + line + w] * blend1)); } } //u v for(h = 0; h <(part->size); h+=2) { line = (h * width) / 4; for (w = 0; w <(part->size); w+=2) { frame[u_pos + line + (w / 2)] = CLIP((part->U * blend) + (frame[u_pos + line + (w / 2)] * blend1)); frame[v_pos + line + (w / 2)] = CLIP((part->V * blend) + (frame[v_pos + line + (w / 2)] * blend1)); } } } part++; } /*free the random seed generator*/ gsl_rng_free (r); } #endif /* * Normalize X coordinate * args: * i - pixel position from 0 to width-1 * width - frame width * * returns: * normalized x coordinate (-1 to 1)) */ double normX(int i, int width) { if(i<0 ) return -1.0; if(i>= width) return 1.0; double x = (double) ((2 * (double)(i)) / (double)(width)) -1; if(x < -1) return -1; if(x > 1) return 1; return x; } /* * Normalize Y coordinate * args: * j - pixel position from 0 to height-1 * height - frame height * * returns: * normalized y coordinate (-1 to 1)) */ double normY(int j, int height) { if(j<0 ) return -1.0; if(j>= height) return 1.0; double y = (double) ((2 * (double)(j)) / (double)(height)) -1; if(y < -1) return -1; if(y > 1) return 1; return y; } /* * Denormalize X coordinate * args: * x - normalized pixel position from -1 to 1 * width - frame width * * returns: * x coordinate (0 to width -1) */ int denormX(double x, int width) { int i = (int) lround(0.5 * width * (x + 1) -1); if(i < 0) return 0; if(i >= width) return (width -1); return i; } /* * denormalize Y coordinate * args: * y - normalized pixel position from -1 to 1 * height - frame height * * returns: * y coordinate (0 to height -1) */ int denormY(double y, int height) { int j = (int) lround(0.5 * height * (y + 1) -1); if(j < 0) return 0; if(j >= height) return (height -1); return j; } #define PI 3.14159265 #define DPI 6.28318531 #define PI2 1.57079632 /* * fast sin replacement */ double fast_sin(double x) { if(x < -PI) x += DPI; else if (x > PI) x -= DPI; if(x < 0) return ((1.27323954 * x) + (.405284735 * x * x)); else return ((1.27323954 * x) - (.405284735 * x * x)); } /* * fast cos replacement */ double fast_cos(double x) { x += PI2; if(x > PI) x -= DPI; if(x < 0) return ((1.27323954 * x) + (.405284735 * x * x)); else return ((1.27323954 * x) - (.405284735 * x * x)); } /* * fast atan2 replacement */ //LMH0612消除警告,最有可能改错的地方 double fast_atan2( double y, double x ) { if ( (float)x == 0.0f ) { if ( (float)y > 0.0f ) return PI2; if ( (float)y == 0.0f ) return (double)0.0f; return -PI2; } double atan; double z = y/x; if ( (float)fabs( z ) < 1.0f ) { atan = (double)(z/((double)1.0f + (double)0.28f*z*z)); if ( x < (double)0.0f ) { if ( (float)y < 0.0f ) return atan - PI; return atan + PI; } } else { atan = PI2- z/(z*z + (double)0.28f); if ( y < (double)0.0f ) return atan - PI; } return atan; } /* * calculate coordinate in input frame from point in ouptut * (all coordinates are normalized) * args: * x,y - output cordinates * xnew, ynew - pointers to input coordinates * type - type of distortion */ void eval_coordinates (double x, double y, double *xnew, double *ynew, int type) { double phi, radius, radius2; switch (type) { case REND_FX_YUV_POW_DISTORT: radius2 = x*x + y*y; radius = radius2; // pow(radius,2) phi = fast_atan2(y,x); //phi = atan2(y,x); *xnew = radius * fast_cos(phi); *ynew = radius * fast_sin(phi); //*xnew = radius * cos(phi); //*ynew = radius * sin(phi); break; case REND_FX_YUV_POW2_DISTORT: *xnew = x * x * SIGN(x); *ynew = y * y * SIGN(y); break; case REND_FX_YUV_SQRT_DISTORT: default: /* square root radial funtion */ radius2 = x*x + y*y; radius = sqrt(radius2); radius = sqrt(radius); phi = fast_atan2(y,x); //phi = atan2(y,x); *xnew = radius * fast_cos(phi); *ynew = radius * fast_sin(phi); //*xnew = radius * cos(phi); //*ynew = radius * sin(phi); break; } } /* * generate box sizes for box blur and precalculate all possible division values * args: * sigma - standard deviation * n - number of boxes * blur - pointer to blur struct * * asserts: * blur is not NULL * * returns: void */ static void boxes4gauss(int sigma, int n, blur_t* blur) { assert(blur != NULL); if(blur->n == n && blur->sigma == sigma) return; //already done int i = 0; int j = 0; blur->n = n; blur->sigma = sigma; //allocate box sizes array if(blur->bSizes != NULL) free(blur->bSizes); blur->bSizes = calloc((size_t)n, sizeof(int)); double ideal_width = sqrt((12*sigma*sigma/n) + 1); int wl = (int)lround(floor(ideal_width)); if(wl%2==0) wl--; int wu = wl+2; double ideal_m = (n*wl*wl + 4*n*wl + 3*n - 12*sigma*sigma)/(4*wl + 4); int m = (int)lround(ideal_m); //allocate division lookup table if(blur->divTable != NULL) { for(i = 0; i < n; ++i) free(blur->divTable[i]); free(blur->divTable); } blur->divTable = calloc((size_t)n, sizeof(int*)); for(i = 0; i < n; ++i) { blur->bSizes[i] = (i < m) ? wl : wu; blur->bSizes[i] -= 1; blur->bSizes[i] /= 2; //precalculate all possible division values for this box size int divider = blur->bSizes[i] + blur->bSizes[i] + 1; // r + r +1 blur->divTable[i] = calloc((size_t)(256 * divider), sizeof(int)); for(j = 0; j < 256*divider; ++j) blur->divTable[i][j] = j/divider; } } /* * box blur horizontal * args: * scl - source channel (pix buffer) * tcl - temporary channel (pix buffer) * w - width * h - height * r_ind - size indice in box size array * blur - pointer to blur struct * * asserts: * none * * returns: void */ void boxBlurH(uint8_t* scl, uint8_t* tcl, int w, int h, int r_ind, blur_t* blur) { int r = blur->bSizes[r_ind]; int i = 0; int j = 0; for(i = 0; i < h; ++i) { int ti = i*w; int li = ti; int ri = ti+r; int fv = scl[ti]; int lv = scl[ti+w-1]; int val = (r+1)*fv; for(j = 0; j < r; ++j) val += scl[ti+j]; for(j = 0; j <= r; ++j) { val += scl[ri++] - fv; tcl[ti++] = (uint8_t) blur->divTable[r_ind][val] & 0xff; } for(j = r+1; j < w-r; ++j) { val += scl[ri++] - scl[li++]; tcl[ti++] = (uint8_t) blur->divTable[r_ind][val] & 0xff; } for( j =w-r; j < w; ++j) { val += lv - scl[li++]; tcl[ti++] = (uint8_t) blur->divTable[r_ind][val] & 0xff; } } } /* * box blur total * args: * scl - source channel (pix buffer) * tcl - temporary channel (pix buffer) * w - width * h - height * r_ind - iteration index * blur - pointer to blur struct * * asserts: * none * * returns: void */ void boxBlurT(uint8_t* scl, uint8_t* tcl, int w, int h, int r_ind, blur_t* blur) { int r = blur->bSizes[r_ind]; int i = 0; int j = 0; for(i = 0; i < w; ++i) { int ti = i; int li = ti; int ri = ti+r*w; int fv = scl[ti]; int lv = scl[ti+w*(h-1)]; int val = (r+1)*fv; for(j = 0; j < r; ++j) val += scl[ti+j*w]; for(j = 0; j <= r; ++j) { val += scl[ri] - fv; tcl[ti] = (uint8_t) blur->divTable[r_ind][val] & 0xff; ri += w; ti += w; } for(j = r+1; j < h-r; ++j) { val += scl[ri] - scl[li]; tcl[ti] = (uint8_t) blur->divTable[r_ind][val] & 0xff; li += w; ri += w; ti += w; } for(j = h-r; j < h; ++j) { val += lv - scl[li]; tcl[ti] = (uint8_t) blur->divTable[r_ind][val] & 0xff; li += w; ti += w; } } } /* * box blur * args: * scl - source channel (pix buffer) * tcl - temporary channel (pix buffer) * width - channel width * height - channel height * r_ind - size indice in box size array * blur - pointer to blur struct * * asserts: * none * * returns: void */ void boxBlur(uint8_t* scl, uint8_t* tcl, int width, int height, int r_ind, blur_t* blur) { memcpy(tcl, scl, (size_t)(width * height)); boxBlurH(tcl, scl, width, height, r_ind, blur); boxBlurT(scl, tcl, width, height, r_ind, blur); } /* * gaussian blur aprox with 3 box blur iterations * args: * frame - pointer to frame buffer (yu12 format) * width - frame width * height - frame height * sigma - deviation * ind - blur struct index to use * * asserts: * frame is not null * ind is smaller than blur struct array lenght * * returns: void */ void fx_yu12_gauss_blur(uint8_t* frame, int width, int height, int sigma, int ind) { assert(frame != NULL); assert(ind < (int)ARRAY_LENGTH(blur)); if(!tmpbuffer) tmpbuffer = malloc((size_t)(width * height) * 3 / 2); if(!blur[ind]) blur[ind] = calloc(1, sizeof(blur_t)); //iterate 3 times boxes4gauss(sigma, 3, blur[ind]); boxBlur(frame, tmpbuffer, width, height, 0, blur[ind]); boxBlur(tmpbuffer, frame, width, height, 1, blur[ind]); boxBlur(frame, tmpbuffer, width, height, 2, blur[ind]); } /* * distort (lens effect) * args: * frame - pointer to frame buffer (yu12 format) * width - frame width * height - frame height * box_width - central box width where distort is to be applied (if < 10 use frame width) * box_height - central box height where distort is to be applied (if < 10 use frame height) * * asserts: * frame is not null * * returns: void */ void fx_yu12_distort(uint8_t* frame, int width, int height, int box_width, int box_height, int type) { assert(frame != NULL); if(!tmpbuffer) tmpbuffer = malloc((size_t)(width * height * 3 / 2)); memcpy(tmpbuffer, frame, (size_t)(width * height * 3 / 2)); uint8_t *pu = frame + (width*height); uint8_t *pv = pu + (width*height)/4; uint8_t *tpu = tmpbuffer + (width*height); uint8_t *tpv = tpu + (width*height)/4; //index table uint32_t *idx_table = NULL; uint32_t* tb_pu = NULL; uint32_t* tb_pv = NULL; int j = 0; int i = 0; int den_x = 0; int den_y = 0; double x = 0; double y = 0; double xnew = 0; double ynew = 0; uint32_t ind = 0; int start_x = 0; int start_y = 0; if(box_width > 10 && width > box_width) start_x = (width - box_width)/2; else box_width = width; if(box_height > 10 && height > box_height) start_y = (height - box_height)/2; else box_height = height; //choose lookup table switch(type) { case REND_FX_YUV_POW_DISTORT: idx_table = TB_Pow_ind; break; case REND_FX_YUV_POW2_DISTORT: idx_table = TB_Pow2_ind; break; case REND_FX_YUV_SQRT_DISTORT: default: idx_table = TB_Sqrt_ind; break; } if(idx_table == NULL) //fill lookup table { idx_table = calloc((size_t)(width * height * 3 / 2), sizeof(uint32_t)); tb_pu = idx_table + (width * height); tb_pv = tb_pu + (width * height)/4; for(j = 0; j < height; ++j) { y = normY(j, height); for(i = 0; i < width; ++i) { x = normX(i, width); eval_coordinates(x, y, &xnew, &ynew, type); den_x = denormX(xnew, width); den_y = denormY(ynew, height); idx_table[i + (j * width)] = (uint32_t)(den_x + (den_y * width)); } } for(j = 0; j < height/2; ++j) { y = normY(j, height/2); for(i = 0; i < width/2; ++i) { x = normX(i, width/2); eval_coordinates(x, y, &xnew, &ynew, type); den_x = denormX(xnew, width/2); den_y = denormY(ynew, height/2); tb_pu[i + (j * width/2)] = (uint32_t)(den_x + (den_y * width/2)); tb_pv[i + (j * width/2)] = (uint32_t)(den_x + (den_y * width/2)); } } //store the table pointer in the matching global switch(type) { case REND_FX_YUV_POW_DISTORT: TB_Pow_ind = idx_table; break; case REND_FX_YUV_POW2_DISTORT: TB_Pow2_ind = idx_table; break; case REND_FX_YUV_SQRT_DISTORT: default: TB_Sqrt_ind = idx_table; break; } } //apply the distortion //(luma) for (j=0; j< box_height; j++) { for(i=0; i< box_width; i++) { int bi = i + start_x; int bj = j + start_y; ind =(uint32_t)( bi + (bj * box_width)); frame[ind] = tmpbuffer[idx_table[ind]]; } } //chroma tb_pu = idx_table + (width * height); tb_pv = tb_pu + (width * height)/4; for (j=0; j< box_height/2; j++) { for(i=0; i< box_width/2; i++) { int bi = i + start_x/2; int bj = j + start_y/2; ind =(uint32_t)( bi + (bj * box_width/2)); pu[ind] = tpu[tb_pu[ind]]; pv[ind] = tpv[tb_pv[ind]]; } } } /* * Apply fx filters * args: * frame - pointer to frame buffer (yu12 format) * width - frame width * height - frame height * mask - or'ed filter mask * * asserts: * frame is not null * * returns: void */ void render_fx_apply(uint8_t *frame, int width, int height, uint32_t mask) { if(mask != REND_FX_YUV_NOFILT) { #ifdef HAS_GSL if(mask & REND_FX_YUV_PARTICLES) fx_particles (frame, width, height, 20, 4); #endif if(mask & REND_FX_YUV_MIRROR) fx_yu12_mirror(frame, width, height); if(mask & REND_FX_YUV_HALF_MIRROR) fx_yu12_half_mirror (frame, width, height); if(mask & REND_FX_YUV_UPTURN) fx_yu12_upturn(frame, width, height); if(mask & REND_FX_YUV_HALF_UPTURN) fx_yu12_half_upturn(frame, width, height); if(mask & REND_FX_YUV_NEGATE) fx_yuv_negative (frame, width, height); if(mask & REND_FX_YUV_MONOCR) fx_yu12_monochrome (frame, width, height); #ifdef HAS_GSL if(mask & REND_FX_YUV_PIECES) fx_yu12_pieces(frame, width, height, 16 ); #endif if(mask & REND_FX_YUV_SQRT_DISTORT) fx_yu12_distort(frame, width, height, 0, 0, REND_FX_YUV_SQRT_DISTORT); if(mask & REND_FX_YUV_POW_DISTORT) fx_yu12_distort(frame, width, height, 0, 0, REND_FX_YUV_POW_DISTORT); if(mask & REND_FX_YUV_POW2_DISTORT) fx_yu12_distort(frame, width, height, 0, 0, REND_FX_YUV_POW2_DISTORT); if(mask & REND_FX_YUV_BLUR) fx_yu12_gauss_blur(frame, width, height, 2, 0); if(mask & REND_FX_YUV_BLUR2) fx_yu12_gauss_blur(frame, width, height, 6, 1); } else render_clean_fx(); } /* * clean fx filters * args: * none * * asserts: * none * * returns: void */ void render_clean_fx() { if(particles != NULL) { free(particles); particles = NULL; } int j = 0; for(j = 0; j < 2; ++j) { if(blur[j] != NULL) { if(blur[j]->bSizes != NULL) free(blur[j]->bSizes); if(blur[j]->divTable != NULL) { int i = 0; for(i = 0; i < blur[j]->n; ++i) free(blur[j]->divTable[i]); free(blur[j]->divTable); } free(blur[j]); blur[j] = NULL; } } if(tmpbuffer != NULL) { free(tmpbuffer); tmpbuffer = NULL; } if(TB_Sqrt_ind != NULL) { free(TB_Sqrt_ind); TB_Sqrt_ind = NULL; } if(TB_Pow_ind != NULL) { free(TB_Pow_ind); TB_Pow_ind = NULL; } if(TB_Pow2_ind != NULL) { free(TB_Pow2_ind); TB_Pow2_ind = NULL; } }
30,595
C
.c
1,177
22.57859
117
0.562534
linuxdeepin/dtkmultimedia
3
16
2
LGPL-3.0
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,285,530
render_osd_vu_meter.c
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam_render/render_osd_vu_meter.c
/*******************************************************************************# # guvcview http://guvcview.sourceforge.net # # # # Paulo Assis <[email protected]> # # Nobuhiro Iwamatsu <[email protected]> # # Add UYVY color support(Macbook iSight) # # Flemming Frandsen <[email protected]> # # Add VU meter OSD # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 2 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program; if not, write to the Free Software # # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # ********************************************************************************/ #include <assert.h> #include <math.h> #include "gview.h" #include "gviewrender.h" extern int verbosity; typedef struct _yuv_color_t { uint8_t y; uint8_t u; uint8_t v; } yuv_color_t; #define REFERENCE_LEVEL 0.8 #define VU_BARS 20 static float vu_peak[2] = {0.0, 0.0}; static float vu_peak_freeze[2]= {0.0 ,0.0}; /* * plot a rectangular box in a yu12 frame (planar) * args: * frame - pointer to yu12 frame data * lines - number of lines in frame (height) * linesize - frame line size in pixels (width) * x - box top left x coordinate * y - box top left y coordinate * width - box width * height - box height * color - box color * * asserts: * none * * returns: none */ static void plot_box_yu12(uint8_t *frame, int lines, int linesize, int x, int y, int width, int height, yuv_color_t *color) { uint8_t *py = frame; uint8_t *pu = frame + (linesize * lines); uint8_t *pv = pu + ((linesize * lines) / 4); /*y*/ int h = 0; for(h = 0; h < height; ++h) { py = frame + x + ((y + h) * linesize); int w = 0; for(w = 0; w < width; ++w) { *py++ = color->y; } } /*u v*/ for(h = 0; h < height/2; h++) /*every two lines*/ { pu = frame + (linesize * lines) + (int) floor(x/2) + (( (int) floor(y/2) + h) * (int) floor(linesize/2)); pv = pu + (int) floor((linesize * lines) / 4); int w = 0; for(w = 0; w < width/2; w++) /*every two rows*/ { *pu++ = color->u; *pv++ = color->v; } } } /* * plot a line in a yu12 frame (planar) * args: * frame - pointer to yu12 frame data * lines - number of lines in frame (height) * linesize - frame line size in pixels (width) * x - box top left x coordinate * y - box top left y coordinate * width - line width * color - line color * * asserts: * none * * returns: none */ static void plot_line_yu12(uint8_t *frame, int lines, int linesize, int x, int y, int width, yuv_color_t *color) { uint8_t *py = frame; uint8_t *pu = frame + (linesize * lines); uint8_t *pv = pu + ((linesize * lines) / 4); int w = 0; /*y*/ py = frame + x + (y * linesize); for(w = 0; w < width; ++w) { *py++ = color->y; } /*u v*/ pu = frame + (linesize * lines) + (int) floor(x/2) + ((int) floor(y/2) * (int) floor(linesize/2)); pv = pu + (int) floor((linesize * lines) / 4); for(w = 0; w < width/2; w ++) /*every two rows*/ { *pu++ = color->u; *pv++ = color->v; } } /* * render a vu meter * args: * frame - pointer to yuyv frame data * width - frame width * height - frame height * vu_level - vu level values (array with 2 channels) * * asserts: * none * * returns: none */ void render_osd_vu_meter(uint8_t *frame, int width, int height, float vu_level[2]) { int bw = 2 * (width / (VU_BARS * 8)); /*make it at least two pixels*/ int bh = height / 24; int channel; for (channel = 0; channel < 2; ++channel) { if((render_get_osd_mask() & REND_OSD_VUMETER_MONO) != 0 && channel > 0) continue; /*if mono mode only render first channel*/ /*make sure we have a positive value (required by log10)*/ if(vu_level[channel] < 0) vu_level[channel] = -vu_level[channel]; /* Handle peak calculation and falloff */ if (vu_peak[channel] < vu_level[channel]) { vu_peak[channel] = vu_level[channel]; vu_peak_freeze[channel] = 30; } else if (vu_peak_freeze[channel] > 0) { vu_peak_freeze[channel]--; } else if (vu_peak[channel] > vu_level[channel]) { vu_peak[channel] -= (vu_peak[channel] - vu_level[channel]) / 10; } /*by default no bar is light */ float dBuLevel = - 4 * (VU_BARS - 1); float dBuPeak = - 4 * (VU_BARS - 1); if(vu_level[channel] > 0) dBuLevel = 10 * log10(vu_level[channel] / REFERENCE_LEVEL); if(vu_peak[channel] > 0) dBuPeak = 10 * log10(vu_peak[channel] / REFERENCE_LEVEL); /* draw the bars */ int peaked = 0; int box = 0; for (box = 0; box <= (VU_BARS - 1); ++box) { /* * The dB it takes to light the current box * step of 2 db between boxes */ float db = 2 * (box - (VU_BARS - 1)); /* start x coordinate for box */ int bx = box * (bw + 4) + (16); /* Start y coordinate for box (box top)*/ int by = channel * (bh + 4) + bh; yuv_color_t color; color.y = 127; color.u = 127; color.v = 127; /*green bar*/ if (db < -10) { color.y = 154; color.u = 72; color.v = 57; } else if (db < -2) /*yellow bar*/ { color.y = 203; color.u = 44; color.v = 142; } else /*red bar*/ { color.y = 107; color.u = 100; color.v = 212; } int light = dBuLevel > db; if (dBuPeak < db+1 && !peaked) { peaked = 1; light = 1; } if (light) plot_box_yu12(frame, height, width, bx, by, bw, bh, &color); else if (bw > 0) /*draw single line*/ plot_line_yu12(frame, height, width, bx, by + (bh /2), bw, &color); } } }
6,886
C
.c
218
28.793578
123
0.519952
linuxdeepin/dtkmultimedia
3
16
2
LGPL-3.0
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
15,285,532
audio.c
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam_audio/audio.c
/*******************************************************************************# # guvcview http://guvcview.sourceforge.net # # # # Paulo Assis <[email protected]> # # Nobuhiro Iwamatsu <[email protected]> # # Add UYVY color support(Macbook iSight) # # Flemming Frandsen <[email protected]> # # Add VU meter OSD # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 2 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program; if not, write to the Free Software # # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # ********************************************************************************/ /*******************************************************************************# # # # Audio library # # # ********************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <math.h> #include <errno.h> #include <assert.h> /* support for internationalization - i18n */ #include <locale.h> #include <libintl.h> #include "cameraconfig.h" #include "gviewaudio.h" #include "audio.h" #include "gview.h" #include "audio_portaudio.h" #if HAS_PULSEAUDIO #include "audio_pulseaudio.h" #endif #define AUDBUFF_NUM 80 /*number of audio buffers*/ #define AUDBUFF_FRAMES 1152 /*number of audio frames per buffer*/ static audio_buff_t *audio_buffers = NULL; /*pointer to buffers list*/ static int buffer_read_index = 0; /*current read index of buffer list*/ static int buffer_write_index = 0;/*current write index of buffer list*/ extern int verbosity; /* * set verbosity * args: * value - verbosity value * * asserts: * none * * returns: none */ void audio_set_verbosity(int value) { verbosity = value; } /* * Lock the mutex * args: * none * * asserts: * none * * returns: none */ void audio_lock_mutex(audio_context_t *audio_ctx) { __LOCK_MUTEX(&(audio_ctx->mutex)); } /* * Unlock the mutex * args: * none * * asserts: * none * * returns: none */ void audio_unlock_mutex(audio_context_t *audio_ctx) { __UNLOCK_MUTEX(&(audio_ctx->mutex)); } /* * free audio buffers * args: * none * * asserts: * none * * returns: error code */ static void audio_free_buffers() { buffer_read_index = 0; buffer_write_index = 0; /*return if no buffers set*/ if(!audio_buffers) { if(verbosity > 0) fprintf(stderr,"AUDIO: can't free audio buffers (audio_free_buffers): audio_buffers is null\n"); return; } int i = 0; for(i = 0; i < AUDBUFF_NUM; ++i) { free(audio_buffers[i].data); } free(audio_buffers); audio_buffers = NULL; } /* * alloc a single audio buffer * args: * audio_ctx - pointer to audio context data * * asserts: * none * * returns: pointer to newly allocate audio buffer or NULL on error * must be freed with audio_delete_buffer * data is allocated for float(32 bit) samples but can also store * int16 (16 bit) samples */ audio_buff_t *audio_get_buffer(audio_context_t *audio_ctx) { if(audio_ctx->capture_buff_size <= 0) { fprintf(stderr, "AUDIO: (get_buffer) invalid capture_buff_size(%i)\n", audio_ctx->capture_buff_size); return NULL; } audio_buff_t *audio_buff = calloc(1, sizeof(audio_buff_t)); if(audio_buff == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (audio_get_buffer): %s\n", strerror(errno)); exit(-1); } audio_buff->data = calloc(audio_ctx->capture_buff_size, sizeof(sample_t)); if(audio_buff->data == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (audio_get_buffer): %s\n", strerror(errno)); exit(-1); } return audio_buff; } /* * deletes a single audio buffer * args: * audio_buff - pointer to audio_buff_t data * * asserts: * none * * returns: none */ void audio_delete_buffer(audio_buff_t *audio_buff) { if(!audio_buff) return; if(audio_buff->data) free(audio_buff->data); free(audio_buff); } /* * alloc audio buffers * args: * audio_ctx - pointer to audio context data * * asserts: * none * * returns: error code */ static int audio_init_buffers(audio_context_t *audio_ctx) { if(!audio_ctx) return -1; /*don't allocate if no audio*/ if(audio_ctx->api == AUDIO_NONE) { audio_buffers = NULL; return 0; } int i = 0; /*set the buffers size*/ if(!audio_ctx->capture_buff_size) audio_ctx->capture_buff_size = audio_ctx->channels * AUDBUFF_FRAMES; if(audio_ctx->capture_buff) free(audio_ctx->capture_buff); audio_ctx->capture_buff = calloc( audio_ctx->capture_buff_size, sizeof(sample_t)); if(audio_ctx->capture_buff == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (audio_init_buffers): %s\n", strerror(errno)); exit(-1); } /*free audio_buffers (if any)*/ audio_free_buffers(); audio_buffers = calloc(AUDBUFF_NUM, sizeof(audio_buff_t)); if(audio_buffers == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (audio_init_buffers): %s\n", strerror(errno)); exit(-1); } for(i = 0; i < AUDBUFF_NUM; ++i) { audio_buffers[i].data = calloc( audio_ctx->capture_buff_size, sizeof(sample_t)); if(audio_buffers[i].data == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (audio_init_buffers): %s\n", strerror(errno)); exit(-1); } audio_buffers[i].flag = AUDIO_BUFF_FREE; } return 0; } /* * fill a audio buffer data and move write index to next one * args: * audio_ctx - pointer to audio context data * ts - timestamp for end of data * * asserts: * audio_ctx is not null * * returns: none */ void audio_fill_buffer(audio_context_t *audio_ctx, int64_t ts) { /*assertions*/ assert(audio_ctx != NULL); if(verbosity > 3) printf("AUDIO: filling buffer ts:%" PRId64 "\n", ts); /*in nanosec*/ uint64_t frame_length = NSEC_PER_SEC / audio_ctx->samprate; uint64_t buffer_length = frame_length * (audio_ctx->capture_buff_size / audio_ctx->channels); audio_ctx->current_ts += buffer_length; /*buffer end time*/ audio_ctx->ts_drift = audio_ctx->current_ts - ts; /*get the current write indexed buffer flag*/ audio_lock_mutex(audio_ctx); int flag = audio_buffers[buffer_write_index].flag; audio_unlock_mutex(audio_ctx); if(flag == AUDIO_BUFF_USED) { fprintf(stderr, "AUDIO: write buffer(%i) is still in use - dropping data\n", buffer_write_index); return; } /*write max_frames and fill a buffer*/ memcpy(audio_buffers[buffer_write_index].data, audio_ctx->capture_buff, audio_ctx->capture_buff_size * sizeof(sample_t)); /*buffer begin time*/ audio_buffers[buffer_write_index].timestamp = audio_ctx->current_ts - buffer_length; if(audio_buffers[buffer_write_index].timestamp < 0) fprintf(stderr, "AUDIO: write buffer(%i) - invalid timestamp (< 0): cur_ts:%" PRId64 " buf_length:%" PRId64 "\n", buffer_write_index, audio_ctx->current_ts, buffer_length); audio_buffers[buffer_write_index].level_meter[0] = audio_ctx->capture_buff_level[0]; audio_buffers[buffer_write_index].level_meter[1] = audio_ctx->capture_buff_level[1]; audio_lock_mutex(audio_ctx); audio_buffers[buffer_write_index].flag = AUDIO_BUFF_USED; NEXT_IND(buffer_write_index, AUDBUFF_NUM); audio_unlock_mutex(audio_ctx); } /* saturate float samples to int16 limits*/ static int16_t clip_int16 (float in) { //int16_t out = (int16_t) (in < -32768) ? -32768 : (in > 32767) ? 32767 : in; long lout = lroundf(in); int16_t out = (lout < INT16_MIN) ? INT16_MIN : (lout > INT16_MAX) ? INT16_MAX: (int16_t) lout; return (out); } /* * get the next used buffer from the ring buffer * args: * audio_ctx - pointer to audio context * buff - pointer to an allocated audio buffer * type - type of data (SAMPLE_TYPE_[INT16|FLOAT]) * mask - audio fx mask * * asserts: * none * * returns: error code */ int audio_get_next_buffer(audio_context_t *audio_ctx, audio_buff_t *buff, int type, uint32_t mask) { audio_lock_mutex(audio_ctx); int flag = audio_buffers[buffer_read_index].flag; audio_unlock_mutex(audio_ctx); if(flag == AUDIO_BUFF_FREE) return 1; /*all done*/ /*aplly fx*/ audio_fx_apply(audio_ctx, (sample_t *) audio_buffers[buffer_read_index].data, mask); /*copy data into requested format type*/ int i = 0; switch(type) { case GV_SAMPLE_TYPE_FLOAT: { sample_t *my_data = (sample_t *) buff->data; memcpy( my_data, audio_buffers[buffer_read_index].data, audio_ctx->capture_buff_size * sizeof(sample_t)); break; } case GV_SAMPLE_TYPE_INT16: { int16_t *my_data = (int16_t *) buff->data; sample_t *buff_p = (sample_t *) audio_buffers[buffer_read_index].data; for(i = 0; i < audio_ctx->capture_buff_size; ++i) { my_data[i] = clip_int16( (buff_p[i]) * INT16_MAX); } break; } case GV_SAMPLE_TYPE_FLOATP: { int j=0; float *my_data[audio_ctx->channels]; sample_t *buff_p = (sample_t *) audio_buffers[buffer_read_index].data; for(j = 0; j < audio_ctx->channels; ++j) my_data[j] = (float *) (((float *) buff->data) + (j * audio_ctx->capture_buff_size/audio_ctx->channels)); for(i = 0; i < audio_ctx->capture_buff_size/audio_ctx->channels; ++i) for(j = 0; j < audio_ctx->channels; ++j) { my_data[j][i] = *buff_p++; } break; } case GV_SAMPLE_TYPE_INT16P: { int j=0; int16_t *my_data[audio_ctx->channels]; sample_t *buff_p = (sample_t *) audio_buffers[buffer_read_index].data; for(j = 0; j < audio_ctx->channels; ++j) my_data[j] = (int16_t *) (((int16_t *) buff->data) + (j * audio_ctx->capture_buff_size/audio_ctx->channels)); for(i = 0; i < audio_ctx->capture_buff_size/audio_ctx->channels; ++i) for(j = 0; j < audio_ctx->channels; ++j) { my_data[j][i] = clip_int16((*buff_p++) * INT16_MAX); } break; } } buff->timestamp = audio_buffers[buffer_read_index].timestamp; buff->level_meter[0] = audio_buffers[buffer_read_index].level_meter[0]; buff->level_meter[1] = audio_buffers[buffer_read_index].level_meter[1]; audio_lock_mutex(audio_ctx); audio_buffers[buffer_read_index].flag = AUDIO_BUFF_FREE; NEXT_IND(buffer_read_index, AUDBUFF_NUM); audio_unlock_mutex(audio_ctx); return 0; } /* * audio initialization * args: * api - audio API to use * (AUDIO_NONE, AUDIO_PORTAUDIO, AUDIO_PULSE, ...) * device - api device index to use (-1 - use api default) * * asserts: * none * * returns: pointer to audio context data (or NULL on error) */ audio_context_t *audio_init(int api, int device) { audio_context_t *audio_ctx = calloc(1, sizeof(audio_context_t)); if(audio_ctx == NULL) { fprintf(stderr, "AUDIO: (audio_init) couldn't allocate audio context\n"); return NULL; } /*initialize the mutex*/ __INIT_MUTEX(&(audio_ctx->mutex)); int ret = 0; switch(api) { case AUDIO_NONE: audio_ctx->api = AUDIO_NONE; break; #if HAS_PULSEAUDIO case AUDIO_PULSE: ret = audio_init_pulseaudio(audio_ctx); break; #endif case AUDIO_PORTAUDIO: default: ret = audio_init_portaudio(audio_ctx); break; } /*if api couldn't be initialized set audio to none*/ if (ret != 0) audio_ctx->api = AUDIO_NONE; /*set default api device*/ audio_set_device_index(audio_ctx, device); /*force a valid number of channels*/ if(audio_ctx->channels > 2) audio_ctx->channels = 2; return audio_ctx; } /* * get audio api * args: * audio_ctx - pointer to audio context data * * asserts: * audio_ctx is not null * * returns: audio API */ int audio_get_api(audio_context_t *audio_ctx) { /*assertions*/ assert(audio_ctx != NULL); return audio_ctx->api; } /* * set the audio device index to use * args: * audio_ctx - pointer to audio context data * index - device index (from device list) to set * * asserts: * audio_ctx is not null * * returns: none */ void audio_set_device_index(audio_context_t *audio_ctx, int index) { /*assertions*/ assert(audio_ctx != NULL); switch(audio_ctx->api) { case AUDIO_NONE: break; #if HAS_PULSEAUDIO case AUDIO_PULSE: audio_set_pulseaudio_device(audio_ctx, index); break; #endif case AUDIO_PORTAUDIO: default: audio_set_portaudio_device(audio_ctx, index); break; } } /* * get the current audio device index * args: * audio_ctx - pointer to audio context data * * asserts: * audio_ctx is not null * * returns: current device index (from device list) */ int audio_get_device_index(audio_context_t *audio_ctx) { /*assertions*/ assert(audio_ctx != NULL); return audio_ctx->device; } /* * get the number of available input audio devices * args: * audio_ctx - pointer to audio context data * * asserts: * audio_ctx is not null * * returns: number of listed audio devices */ int audio_get_num_inp_devices(audio_context_t *audio_ctx) { /*assertions*/ assert(audio_ctx != NULL); return audio_ctx->num_input_dev; } /* * get the audio device referenced by index * args: * audio_ctx - pointer to audio context data * index - index of audio device * * asserts: * audio_ctx is not null * * returns: audio device referenced by index */ audio_device_t* audio_get_device(audio_context_t *audio_ctx, int index) { /*assertions*/ assert(audio_ctx != NULL); if(index >= audio_ctx->num_input_dev) { fprintf(stderr, "AUDIO: (audio_get_device) bad index %i using %i\n", index, audio_ctx->num_input_dev - 1); index = audio_ctx->num_input_dev - 1; } if(index < 0) { fprintf(stderr, "AUDIO: (audio_get_device) bad index %i using 0\n", index); index = 0; } return &audio_ctx->list_devices[index]; } /* * set the current latency * args: * audio_ctx - pointer to audio context data * * asserts: * audio_ctx is not null * * returns: none */ void audio_set_latency(audio_context_t *audio_ctx, double latency) { /*assertions*/ assert(audio_ctx != NULL); audio_ctx->latency = latency; } /* * get the current latency * args: * audio_ctx - pointer to audio context data * * asserts: * audio_ctx is not null * * returns: defined lantency */ double audio_get_latency(audio_context_t *audio_ctx) { /*assertions*/ assert(audio_ctx != NULL); return audio_ctx->latency; } /* * set the number of channels * args: * audio_ctx - pointer to audio context data * * asserts: * audio_ctx is not null * * returns: none */ void audio_set_channels(audio_context_t *audio_ctx, int channels) { /*assertions*/ assert(audio_ctx != NULL); audio_ctx->channels = channels; } /* * get the number of channels * args: * audio_ctx - pointer to audio context data * * asserts: * audio_ctx is not null * * returns: number of channels */ int audio_get_channels(audio_context_t *audio_ctx) { /*assertions*/ assert(audio_ctx != NULL); return audio_ctx->channels; } /* * set the sample rate * args: * audio_ctx - pointer to audio context data * * asserts: * audio_ctx is not null * * returns: none */ void audio_set_samprate(audio_context_t *audio_ctx, int samprate) { /*assertions*/ assert(audio_ctx != NULL); audio_ctx->samprate = samprate; } /* * get the sample rate * args: * audio_ctx - pointer to audio context data * * asserts: * audio_ctx is not null * * returns: sample rate */ int audio_get_samprate(audio_context_t *audio_ctx) { /*assertions*/ assert(audio_ctx != NULL); return audio_ctx->samprate; } /* * set the capture buffer size * args: * audio_ctx - pointer to audio context data * size - capture buffer size in bytes * * asserts: * audio_ctx is not null * * returns: none */ void audio_set_cap_buffer_size(audio_context_t *audio_ctx, int size) { /*assertions*/ assert(audio_ctx != NULL); if(verbosity > 2) printf("AUDIO: set capture buffer size to %i samples\n", size); audio_ctx->capture_buff_size = size; } /* * start audio stream capture * args: * audio_ctx - pointer to audio context data * * asserts: * audio_ctx is not null * * returns: error code */ int audio_start(audio_context_t *audio_ctx) { if(verbosity > 1) printf("AUDIO: starting audio capture\n"); /*assertions*/ assert(audio_ctx != NULL); /*alloc the ring buffer*/ audio_init_buffers(audio_ctx); /*reset timestamp values*/ audio_ctx->current_ts = 0; audio_ctx->last_ts = 0; audio_ctx->snd_begintime = 0; audio_ctx->ts_drift = 0; int err = 0; switch(audio_ctx->api) { case AUDIO_NONE: break; #if HAS_PULSEAUDIO case AUDIO_PULSE: err = audio_start_pulseaudio(audio_ctx); break; #endif case AUDIO_PORTAUDIO: default: err = audio_start_portaudio(audio_ctx); break; } return err; } /* * stop audio stream capture * args: * audio_ctx - pointer to audio context data * * asserts: * audio_ctx is not null * * returns: error code */ int audio_stop(audio_context_t *audio_ctx) { /*assertions*/ assert(audio_ctx != NULL); int err =0; switch(audio_ctx->api) { case AUDIO_NONE: break; #if HAS_PULSEAUDIO case AUDIO_PULSE: err = audio_stop_pulseaudio(audio_ctx); break; #endif case AUDIO_PORTAUDIO: default: err = audio_stop_portaudio(audio_ctx); break; } /*free the ring buffer (if any)*/ audio_free_buffers(); return err; } /* * close and clean audio context * args: * audio_ctx - pointer to audio context data * * asserts: * audio_ctx is not null * * returns: none */ void audio_close(audio_context_t *audio_ctx) { /*assertions*/ assert(audio_ctx != NULL); audio_fx_close(); /* thread must be joined before destroying the mutex * so no need to unlock before destroying it */ /*destroy the mutex*/ __CLOSE_MUTEX(&(audio_ctx->mutex)); switch(audio_ctx->api) { case AUDIO_NONE: break; #if HAS_PULSEAUDIO case AUDIO_PULSE: audio_close_pulseaudio(audio_ctx); break; #endif case AUDIO_PORTAUDIO: default: audio_close_portaudio(audio_ctx); break; } if(audio_buffers != NULL) audio_free_buffers(); }
19,489
C
.c
750
23.710667
116
0.637604
linuxdeepin/dtkmultimedia
3
16
2
LGPL-3.0
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
15,285,533
audio_portaudio.c
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam_audio/audio_portaudio.c
/*******************************************************************************# # guvcview http://guvcview.sourceforge.net # # # # Paulo Assis <[email protected]> # # Nobuhiro Iwamatsu <[email protected]> # # Add UYVY color support(Macbook iSight) # # Flemming Frandsen <[email protected]> # # Add VU meter OSD # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 2 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program; if not, write to the Free Software # # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # ********************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <errno.h> #include <assert.h> #include <portaudio.h> /* support for internationalization - i18n */ #include <locale.h> #include <libintl.h> #include "gview.h" #include "audio.h" #include "core_time.h" #include "gviewaudio.h" #include "load_libs.h" extern int verbosity; static int sample_index = 0; #define DEFAULT_LATENCY_DURATION 100.0 /* * Portaudio record callback * args: * inputBuffer - pointer to captured input data (for recording) * outputBuffer - pointer ouput data (for playing - NOT USED) * framesPerBuffer - buffer size * timeInfo - pointer to time data (for timestamping) * statusFlags - stream status * userData - pointer to user data (audio context) * * asserts: * audio_ctx (userData) is not null * * returns: error code (0 ok) */ static int recordCallback ( const void *inputBuffer, __attribute__((unused)) void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *userData ) { audio_context_t *audio_ctx = (audio_context_t *) userData; /*asserts*/ assert(audio_ctx != NULL); if(audio_ctx->channels == 0) { fprintf(stderr, "AUDIO: (portaudio) recordCallback failed: channels = 0\n"); return (paContinue); } if(audio_ctx->samprate == 0) { fprintf(stderr, "AUDIO: (portaudio) recordCallback failed: samprate = 0\n"); return (paContinue); } uint32_t i = 0; sample_t *rptr = (sample_t*) inputBuffer; sample_t *capture_buff = (sample_t *) audio_ctx->capture_buff; unsigned long numSamples = framesPerBuffer * audio_ctx->channels; uint64_t frame_length = NSEC_PER_SEC / audio_ctx->samprate; /*in nanosec (is never 0)*/ PaTime ts_sec = timeInfo->inputBufferAdcTime; /*in seconds (double)*/ int64_t ts = ts_sec * NSEC_PER_SEC; /*in nanosec (monotonic time)*/ int64_t buff_ts = 0; /*determine the number of samples dropped*/ if(audio_ctx->last_ts <= 0) { audio_ctx->last_ts = ts; } if(statusFlags & paInputOverflow) { fprintf( stderr, "AUDIO: portaudio buffer overflow\n" ); int64_t d_ts = ts - audio_ctx->last_ts; uint32_t n_samples = (d_ts / frame_length) * audio_ctx->channels; for( i = 0; i < n_samples; ++i ) { capture_buff[sample_index] = 0; sample_index++; if(sample_index >= audio_ctx->capture_buff_size) { audio_fill_buffer(audio_ctx, audio_ctx->last_ts); sample_index = 0; } } if(verbosity > 1) printf("AUDIO: compensate overflow with %u silence samples\n", n_samples); } if(statusFlags & paInputUnderflow) fprintf( stderr, "AUDIO: portaudio buffer underflow\n" ); if(sample_index == 0) { audio_ctx->capture_buff_level[0] = 0; audio_ctx->capture_buff_level[1] = 0; } int chan = 0; /*store capture samples*/ for( i = 0; i < numSamples; ++i ) { capture_buff[sample_index] = inputBuffer ? *rptr++ : 0; if(sample_index < audio_ctx->capture_buff_size){ /*store peak value*/ if(audio_ctx->capture_buff_level[chan] < capture_buff[sample_index]) audio_ctx->capture_buff_level[chan] = capture_buff[sample_index]; chan++; if(chan >= audio_ctx->channels) chan = 0; } sample_index++; if(sample_index >= audio_ctx->capture_buff_size) { buff_ts = ts + ( i / audio_ctx->channels ) * frame_length; audio_fill_buffer(audio_ctx, buff_ts); /*reset*/ audio_ctx->capture_buff_level[0] = 0; audio_ctx->capture_buff_level[1] = 0; sample_index = 0; } } audio_ctx->last_ts = ts + (framesPerBuffer * frame_length); if(audio_ctx->stream_flag == AUDIO_STRM_OFF ) return (paComplete); /*capture stopped*/ else return (paContinue); /*still capturing*/ } /* * list audio devices for portaudio api * args: * audio_ctx - pointer to audio context data * asserts: * audio_ctx is not null * * returns: error code (0 ok) */ static int audio_portaudio_list_devices(audio_context_t *audio_ctx) { /*asserts*/ assert(audio_ctx != NULL); int numDevices; const PaDeviceInfo *deviceInfo; //reset device count audio_ctx->num_input_dev = 0; numDevices = getPortAudio()->m_Pa_GetDeviceCount(); if( numDevices < 0 ) { printf( "AUDIO: Audio disabled: Pa_CountDevices returned %i\n", numDevices ); } else { audio_ctx->device = 0; int it = 0; for( it=0; it < numDevices; it++ ) { deviceInfo = getPortAudio()->m_Pa_GetDeviceInfo( it ); if (verbosity > 0) printf( "--------------------------------------- device #%d\n", it ); /* Mark audio_ctx and API specific default devices*/ int defaultDisplayed = 0; /* with pulse, ALSA is now listed first and doesn't set a API default- 11-2009*/ if( it == getPortAudio()->m_Pa_GetDefaultInputDevice() ) { if (verbosity > 0) printf( "[ Default Input" ); defaultDisplayed = 1; audio_ctx->device = audio_ctx->num_input_dev;/*default index in array of input devs*/ } else if( it == getPortAudio()->m_Pa_GetHostApiInfo( deviceInfo->hostApi )->defaultInputDevice ) { const PaHostApiInfo *hostInfo = getPortAudio()->m_Pa_GetHostApiInfo( deviceInfo->hostApi ); if (verbosity > 0) printf( "[ Default %s Input", hostInfo->name ); defaultDisplayed = 2; } /* OUTPUT device doesn't matter for capture*/ if( it == getPortAudio()->m_Pa_GetDefaultOutputDevice() ) { if (verbosity > 0) { printf( (defaultDisplayed ? "," : "[") ); printf( " Default Output" ); } defaultDisplayed = 3; } else if( it == getPortAudio()->m_Pa_GetHostApiInfo( deviceInfo->hostApi )->defaultOutputDevice ) { const PaHostApiInfo *hostInfo = getPortAudio()->m_Pa_GetHostApiInfo( deviceInfo->hostApi ); if (verbosity > 0) { printf( (defaultDisplayed ? "," : "[") ); printf( " Default %s Output", hostInfo->name );/* OSS ALSA etc*/ } defaultDisplayed = 4; } if( defaultDisplayed!=0 ) if (verbosity > 0) printf( " ]\n" ); /* print device info fields */ if (verbosity > 0) { printf( "Name = %s\n", deviceInfo->name ); printf( "Host API = %s\n", getPortAudio()->m_Pa_GetHostApiInfo( deviceInfo->hostApi )->name ); printf( "Max inputs = %d", deviceInfo->maxInputChannels ); } /* INPUT devices (if it has input channels it's a capture device)*/ if (deviceInfo->maxInputChannels > 0) { audio_ctx->num_input_dev++; /*add device to list*/ audio_ctx->list_devices = realloc(audio_ctx->list_devices, audio_ctx->num_input_dev * sizeof(audio_device_t)); if(audio_ctx->list_devices == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (audio_portaudio_list_devices): %s\n", strerror(errno)); exit(-1); } /*fill device data*/ audio_ctx->list_devices[audio_ctx->num_input_dev-1].id = it; strncpy(audio_ctx->list_devices[audio_ctx->num_input_dev-1].name, deviceInfo->name, 511); strncpy(audio_ctx->list_devices[audio_ctx->num_input_dev-1].description, deviceInfo->name, 255); audio_ctx->list_devices[audio_ctx->num_input_dev-1].channels = deviceInfo->maxInputChannels; audio_ctx->list_devices[audio_ctx->num_input_dev-1].samprate = deviceInfo->defaultSampleRate; audio_ctx->list_devices[audio_ctx->num_input_dev-1].high_latency = (double) deviceInfo->defaultHighInputLatency; audio_ctx->list_devices[audio_ctx->num_input_dev-1].low_latency = (double) deviceInfo->defaultLowInputLatency; } if (verbosity > 0) { printf( ", Max outputs = %d\n", deviceInfo->maxOutputChannels ); printf( "Def. low input latency = %8.3f\n", deviceInfo->defaultLowInputLatency ); printf( "Def. low output latency = %8.3f\n", deviceInfo->defaultLowOutputLatency ); printf( "Def. high input latency = %8.3f\n", deviceInfo->defaultHighInputLatency ); printf( "Def. high output latency = %8.3f\n", deviceInfo->defaultHighOutputLatency ); printf( "Def. sample rate = %8.2f\n", deviceInfo->defaultSampleRate ); } } if (verbosity > 0) printf("----------------------------------------------\n"); } if (audio_ctx->num_input_dev <= 0) { printf( "AUDIO: Audio disabled: no input devices found (%i)\n", audio_ctx->num_input_dev ); return -1; } /*set defaults*/ audio_ctx->channels = audio_ctx->list_devices[audio_ctx->device].channels; audio_ctx->samprate = audio_ctx->list_devices[audio_ctx->device].samprate; return 0; } /* * init portaudio api * args: * audio_ctx - pointer to audio context data * * asserts: * audio_ctx is not null * * returns: error code (0 = E_OK) */ int audio_init_portaudio(audio_context_t* audio_ctx) { /*assertions*/ assert(audio_ctx != NULL); int pa_error = getPortAudio()->m_Pa_Initialize(); if(pa_error != paNoError) { fprintf(stderr,"AUDIO: Failed to Initialize Portaudio (Pa_Initialize returned %i)\n", pa_error); return -1; } if(audio_portaudio_list_devices(audio_ctx) != 0) { fprintf(stderr, "AUDIO: Portaudio failed to get audio device list\n"); return -1; } audio_ctx->api = AUDIO_PORTAUDIO; return 0; } /* * set audio device * args: * audio_ctx - pointer to audio context data * index - device index to set * * asserts: * audio_ctx is not null * * returns: none */ void audio_set_portaudio_device(audio_context_t *audio_ctx, int index) { /*assertions*/ assert(audio_ctx != NULL); if(index >= audio_ctx->num_input_dev) audio_ctx->device = audio_ctx->num_input_dev - 1; else if(index >= 0 ) audio_ctx->device = audio_ctx->num_input_dev - 1; if(verbosity > 1) printf("AUDIO: Portaudio device changed to %i\n", audio_ctx->device); audio_ctx->latency = audio_ctx->list_devices[audio_ctx->device].high_latency; audio_ctx->channels = audio_ctx->list_devices[audio_ctx->device].channels; if(audio_ctx->channels > 2) audio_ctx->channels = 2;/*limit it to stereo input*/ audio_ctx->samprate = audio_ctx->list_devices[audio_ctx->device].samprate; } /* * start portaudio stream capture * args: * audio_ctx - pointer to audio context data * * asserts: * audio_ctx is not null * * returns: error code */ int audio_start_portaudio(audio_context_t *audio_ctx) { /*assertions*/ assert(audio_ctx != NULL); PaError err = paNoError; PaStream *stream = (PaStream *) audio_ctx->stream; if(stream) { if( !(getPortAudio()->m_Pa_IsStreamStopped( stream ))) { getPortAudio()->m_Pa_AbortStream( stream ); getPortAudio()->m_Pa_CloseStream( stream ); audio_ctx->stream = NULL; stream = audio_ctx->stream; } } PaStreamParameters inputParameters; inputParameters.device = audio_ctx->list_devices[audio_ctx->device].id; inputParameters.channelCount = audio_ctx->channels; inputParameters.sampleFormat = paFloat32; /*sample_t - float*/ inputParameters.suggestedLatency = audio_ctx->latency; /*DEFAULT_LATENCY_DURATION/1000.0;*/ inputParameters.hostApiSpecificStreamInfo = NULL; /*---------------------------- start recording Audio. ----------------------------- */ audio_ctx->snd_begintime = ns_time_monotonic(); audio_ctx->stream_flag = AUDIO_STRM_ON; err = getPortAudio()->m_Pa_OpenStream( &stream, /* stream */ &inputParameters, /* inputParameters */ NULL, /* outputParameters */ audio_ctx->samprate, /* sample rate */ paFramesPerBufferUnspecified,/* buffer in frames (use API optimal)*/ paNoFlag, /* PaNoFlag - clip and dhiter*/ recordCallback, /* sound callback */ audio_ctx ); /* callback userData */ if( err == paNoError ) { err = getPortAudio()->m_Pa_StartStream( stream ); audio_ctx->stream = (void *) stream; /* store stream pointer*/ } if( err != paNoError ) { fprintf(stderr, "AUDIO: An error occured while starting the portaudio API\n" ); fprintf(stderr, " Error number: %d\n", err ); fprintf(stderr, " Error message: %s\n", getPortAudio()->m_Pa_GetErrorText( err ) ); if(stream) getPortAudio()->m_Pa_AbortStream( stream ); audio_ctx->stream_flag = AUDIO_STRM_OFF; return(-1); } const PaStreamInfo* stream_info = getPortAudio()->m_Pa_GetStreamInfo (stream); if(verbosity > 1) printf("AUDIO: latency of %8.3f msec\n", 1000 * stream_info->inputLatency); return 0; } /* * stop portaudio stream capture * args: * audio_ctx - pointer to audio context data * * asserts: * audio_ctx is not null * * returns: error code */ int audio_stop_portaudio(audio_context_t *audio_ctx) { /*assertions*/ assert(audio_ctx != NULL); int ret = 0; int err = paNoError; audio_ctx->stream_flag = AUDIO_STRM_OFF; PaStream *stream = (PaStream *) audio_ctx->stream; /*stops and closes the audio stream*/ if(stream) { if(getPortAudio()->m_Pa_IsStreamActive( stream ) > 0) { printf("AUDIO: (portaudio) Aborting audio stream\n"); err = getPortAudio()->m_Pa_AbortStream( stream ); } else { printf("AUDIO: (portaudio) Stoping audio stream\n"); err = getPortAudio()->m_Pa_StopStream( stream ); } if( err != paNoError ) { fprintf(stderr, "AUDIO: (portaudio) An error occured while stoping the audio stream\n" ); fprintf(stderr, " Error number: %d\n", err ); fprintf(stderr, " Error message: %s\n", getPortAudio()->m_Pa_GetErrorText( err ) ); ret = -1; } printf("AUDIO: Closing audio stream...\n"); err = getPortAudio()->m_Pa_CloseStream( stream ); if( err != paNoError ) { fprintf(stderr, "AUDIO: (portaudio) An error occured while closing the audio stream\n" ); fprintf(stderr, " Error number: %d\n", err ); fprintf(stderr, " Error message: %s\n", getPortAudio()->m_Pa_GetErrorText( err ) ); ret = -1; } } else { fprintf(stderr, "AUDIO: (portaudio) Invalid stream pointer.\n"); ret = -2; } audio_ctx->stream = NULL; return ret; } /* * close and clean audio context for portaudio api * args: * audio_ctx - pointer to audio context data * * asserts: * none * * returns: none */ void audio_close_portaudio(audio_context_t *audio_ctx) { getPortAudio()->m_Pa_Terminate(); if(audio_ctx == NULL) return; if(audio_ctx->list_devices != NULL) free(audio_ctx->list_devices); audio_ctx->list_devices = NULL; if(audio_ctx->capture_buff) free(audio_ctx->capture_buff); free(audio_ctx); }
16,675
C
.c
465
32.382796
127
0.619027
linuxdeepin/dtkmultimedia
3
16
2
LGPL-3.0
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
15,285,534
audio_fx.c
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam_audio/audio_fx.c
/*******************************************************************************# # guvcview http://guvcview.sourceforge.net # # # # Paulo Assis <[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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # ********************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <math.h> #include <string.h> #include <errno.h> #include <assert.h> /* support for internationalization - i18n */ #include <locale.h> #include <libintl.h> #include "cameraconfig.h" #include "gviewaudio.h" #include "audio.h" #include "gview.h" #ifndef M_PI #define M_PI 3.14159265358979323846 #endif extern int verbosity; /*----------- structs for audio effects ------------*/ /*data for Butterworth filter (LP or HP)*/ typedef struct _fx_filt_data_t { sample_t buff_in1[2]; sample_t buff_in2[2]; sample_t buff_out1[2]; sample_t buff_out2[2]; float c; float a1; float a2; float a3; float b1; float b2; } fx_filt_data_t; /*data for Comb4 filter*/ typedef struct _fx_comb4_data_t { int buff_size1; int buff_size2; int buff_size3; int buff_size4; sample_t *CombBuff10; // four parallel comb filters - first channel sample_t *CombBuff11; // four parallel comb filters - second channel sample_t *CombBuff20; // four parallel comb filters - first channel sample_t *CombBuff21; // four parallel comb filters - second channel sample_t *CombBuff30; // four parallel comb filters - first channel sample_t *CombBuff31; // four parallel comb filters - second channel sample_t *CombBuff40; // four parallel comb filters - first channel sample_t *CombBuff41; // four parallel comb filters - second channel int CombIndex1; //comb filter 1 index int CombIndex2; //comb filter 2 index int CombIndex3; //comb filter 3 index int CombIndex4; //comb filter 4 index } fx_comb4_data_t; /* data for delay*/ typedef struct _fx_delay_data_t { int buff_size; sample_t *delayBuff1; // delay buffer 1 - first channel sample_t *delayBuff2; // delay buffer 2 - second channel (stereo) int delayIndex; // delay buffer index } fx_delay_data_t; /* data for WahWah effect*/ typedef struct _fx_wah_data_t { float lfoskip; unsigned long skipcount; float xn1; float xn2; float yn1; float yn2; float b0; float b1; float b2; float a0; float a1; float a2; float phase; } fx_wah_data_t; typedef struct _fx_rate_data_t { sample_t *rBuff1; sample_t *rBuff2; sample_t *wBuff1; sample_t *wBuff2; int wSize; int numsamples; } fx_rate_data_t; typedef struct _audio_fx_t { fx_delay_data_t *ECHO; fx_delay_data_t *AP1; fx_comb4_data_t *COMB4; fx_filt_data_t *HPF; fx_filt_data_t *LPF1; fx_rate_data_t *RT1; fx_wah_data_t *wahData; } audio_fx_t; /*audio fx data*/ static audio_fx_t *aud_fx = NULL; /* * initialize audio fx data * args: * none * * asserts: * none * * returns: none */ static void audio_fx_init () { aud_fx = calloc(1, sizeof(audio_fx_t)); if(aud_fx == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (audio_fx_init): %s\n", strerror(errno)); exit(-1); } /*Echo effect data */ aud_fx->ECHO = NULL; /* 4 parallel comb filters data*/ aud_fx->COMB4 = NULL; /*all pass 1 filter data*/ aud_fx->AP1 = NULL; /*WahWah effect data*/ aud_fx->wahData = NULL; /*high pass filter data*/ aud_fx->HPF = NULL; /*rate transposer*/ aud_fx->RT1 = NULL; /*low pass filter*/ aud_fx->LPF1 = NULL; } /* * clip float samples [-1.0 ; 1.0] * args: * in - float sample * * asserts: * none * * returns: float sample */ static float clip_float (float in) { in = (in < -1.0) ? -1.0 : (in > 1.0) ? 1.0 : in; return in; } /* * Butterworth Filter for HP or LP * out(n) = a1 * in + a2 * in(n-1) + a3 * in(n-2) - b1*out(n-1) - b2*out(n-2) * args: * FILT - pointer to fx_filt_data_t * Buff - sampe buffer * NumSamples - samples in buffer * channels - number of audio channels */ static void Butt(fx_filt_data_t *FILT, sample_t *Buff, int NumSamples, int channels) { int index = 0; for (index = 0; index < NumSamples; index = index + channels) { sample_t out = FILT->a1 * Buff[index] + FILT->a2 * FILT->buff_in1[0] + FILT->a3 * FILT->buff_in1[1] - FILT->b1 * FILT->buff_out1[0] - FILT->b2 * FILT->buff_out1[1]; FILT->buff_in1[1] = FILT->buff_in1[0]; //in(n-2) = in(n-1) FILT->buff_in1[0] = Buff[index]; // in(n-1) = in FILT->buff_out1[1] = FILT->buff_out1[0]; //out(n-2) = out(n-1) FILT->buff_out1[0] = out; //out(n-1) = out Buff[index] = clip_float(out); /*process second channel*/ if(channels > 1) { out = FILT->a1 * Buff[index+1] + FILT->a2 * FILT->buff_in2[0] + FILT->a3 * FILT->buff_in2[1] - FILT->b1 * FILT->buff_out2[0] - FILT->b2 * FILT->buff_out2[1]; FILT->buff_in2[1] = FILT->buff_in2[0]; //in(n-2) = in(n-1) FILT->buff_in2[0] = Buff[index+1]; // in(n-1) = in FILT->buff_out2[1] = FILT->buff_out2[0]; //out(n-2) = out(n-1) FILT->buff_out2[0] = out; //out(n-1) = out Buff[index+1] = clip_float(out); } } } /* * HP Filter: out(n) = a1 * in + a2 * in(n-1) + a3 * in(n-2) - b1*out(n-1) - b2*out(n-2) * f - cuttof freq., from ~0 Hz to SampleRate/2 - though many synths seem to filter only up to SampleRate/4 * r = rez amount, from sqrt(2) to ~ 0.1 * * c = tan(pi * f / sample_rate); * a1 = 1.0 / ( 1.0 + r * c + c * c); * a2 = -2*a1; * a3 = a1; * b1 = 2.0 * ( c*c - 1.0) * a1; * b2 = ( 1.0 - r * c + c * c) * a1; * args: * audio_ctx - pointer to audio context * data -pointer to audio buffer to be processed * cutoff_freq - filter cut off frequency * res - rez amount * * asserts: * none * * returns: none */ static void HPF(audio_context_t *audio_ctx, sample_t *data, int cutoff_freq, float res) { if(aud_fx->HPF == NULL) { float inv_samprate = 1.0 / audio_ctx->samprate; aud_fx->HPF = calloc(1, sizeof(fx_filt_data_t)); if(aud_fx->HPF == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (HPF): %s\n", strerror(errno)); exit(-1); } aud_fx->HPF->c = tan(M_PI * cutoff_freq * inv_samprate); aud_fx->HPF->a1 = 1.0 / (1.0 + (res * aud_fx->HPF->c) + (aud_fx->HPF->c * aud_fx->HPF->c)); aud_fx->HPF->a2 = -2.0 * aud_fx->HPF->a1; aud_fx->HPF->a3 = aud_fx->HPF->a1; aud_fx->HPF->b1 = 2.0 * ((aud_fx->HPF->c * aud_fx->HPF->c) - 1.0) * aud_fx->HPF->a1; aud_fx->HPF->b2 = (1.0 - (res * aud_fx->HPF->c) + (aud_fx->HPF->c * aud_fx->HPF->c)) * aud_fx->HPF->a1; } Butt(aud_fx->HPF, data, audio_ctx->capture_buff_size, audio_ctx->channels); } /* * LP Filter: out(n) = a1 * in + a2 * in(n-1) + a3 * in(n-2) - b1*out(n-1) - b2*out(n-2) * f - cuttof freq., from ~0 Hz to SampleRate/2 - * though many synths seem to filter only up to SampleRate/4 * r = rez amount, from sqrt(2) to ~ 0.1 * * c = 1.0 / tan(pi * f / sample_rate); * a1 = 1.0 / ( 1.0 + r * c + c * c); * a2 = 2* a1; * a3 = a1; * b1 = 2.0 * ( 1.0 - c*c) * a1; * b2 = ( 1.0 - r * c + c * c) * a1; * * args: * audio_ctx - pointer to audio context * data -pointer to audio buffer to be processed * cutoff_freq - filter cut off frequency * res - rez amount * * asserts: * none * * returns: none */ static void LPF(audio_context_t *audio_ctx, sample_t *data, float cutoff_freq, float res) { if(aud_fx->LPF1 == NULL) { aud_fx->LPF1 = calloc(1, sizeof(fx_filt_data_t)); if(aud_fx->LPF1 == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (LPF): %s\n", strerror(errno)); exit(-1); } aud_fx->LPF1->c = 1.0 / tan(M_PI * cutoff_freq / audio_ctx->samprate); aud_fx->LPF1->a1 = 1.0 / (1.0 + (res * aud_fx->LPF1->c) + (aud_fx->LPF1->c * aud_fx->LPF1->c)); aud_fx->LPF1->a2 = 2.0 * aud_fx->LPF1->a1; aud_fx->LPF1->a3 = aud_fx->LPF1->a1; aud_fx->LPF1->b1 = 2.0 * (1.0 - (aud_fx->LPF1->c * aud_fx->LPF1->c)) * aud_fx->LPF1->a1; aud_fx->LPF1->b2 = (1.0 - (res * aud_fx->LPF1->c) + (aud_fx->LPF1->c * aud_fx->LPF1->c)) * aud_fx->LPF1->a1; } Butt(aud_fx->LPF1, data, audio_ctx->capture_buff_size, audio_ctx->channels); } /* Non-linear amplifier with soft distortion curve. * args: * input - sample input * * asserts: * none * * returns: processed sample */ static sample_t CubicAmplifier( sample_t input ) { sample_t out; float temp; if( input < 0 ) /*silence*/ { temp = input + 1.0f; out = (temp * temp * temp) - 1.0f; } else { temp = input - 1.0f; out = (temp * temp * temp) + 1.0f; } return clip_float(out); } /* * four paralell Comb filters for reverb * args: * audio_ctx - audio context * data - audio buffer to be processed * delay1_ms - delay for filter 1 * delay2_ms - delay for filter 2 * delay3_ms - delay for filter 3 * delay4_ms - delay for filter 4 * gain1 - feed gain for filter 1 * gain2 - feed gain for filter 2 * gain3 - feed gain for filter 3 * gain4 - feed gain for filter 4 * in_gain - input line gain * * asserts: * none * * returns: none */ static void CombFilter4 (audio_context_t *audio_ctx, sample_t *data, int delay1_ms, int delay2_ms, int delay3_ms, int delay4_ms, float gain1, float gain2, float gain3, float gain4, float in_gain) { int samp=0; /*buff_size in samples*/ if (aud_fx->COMB4 == NULL) { aud_fx->COMB4 = calloc(1, sizeof(fx_comb4_data_t)); if(aud_fx->COMB4 == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (CombFilter4): %s\n", strerror(errno)); exit(-1); } /*buff_size in samples*/ aud_fx->COMB4->buff_size1 = (int) delay1_ms * (audio_ctx->samprate * 0.001); aud_fx->COMB4->buff_size2 = (int) delay2_ms * (audio_ctx->samprate * 0.001); aud_fx->COMB4->buff_size3 = (int) delay3_ms * (audio_ctx->samprate * 0.001); aud_fx->COMB4->buff_size4 = (int) delay4_ms * (audio_ctx->samprate * 0.001); aud_fx->COMB4->CombBuff10 = calloc(aud_fx->COMB4->buff_size1, sizeof(sample_t)); if(aud_fx->COMB4->CombBuff10 == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (CombFilter4): %s\n", strerror(errno)); exit(-1); } aud_fx->COMB4->CombBuff20 = calloc(aud_fx->COMB4->buff_size2, sizeof(sample_t)); if(aud_fx->COMB4->CombBuff20 == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (CombFilter4): %s\n", strerror(errno)); exit(-1); } aud_fx->COMB4->CombBuff30 = calloc(aud_fx->COMB4->buff_size3, sizeof(sample_t)); if(aud_fx->COMB4->CombBuff30 == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (CombFilter4): %s\n", strerror(errno)); exit(-1); } aud_fx->COMB4->CombBuff40 = calloc(aud_fx->COMB4->buff_size4, sizeof(sample_t)); if(aud_fx->COMB4->CombBuff40 == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (CombFilter4): %s\n", strerror(errno)); exit(-1); } aud_fx->COMB4->CombBuff11 = NULL; aud_fx->COMB4->CombBuff21 = NULL; aud_fx->COMB4->CombBuff31 = NULL; aud_fx->COMB4->CombBuff41 = NULL; if(audio_ctx->channels > 1) { aud_fx->COMB4->CombBuff11 = calloc(aud_fx->COMB4->buff_size1, sizeof(sample_t)); if(aud_fx->COMB4->CombBuff11 == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (CombFilter4): %s\n", strerror(errno)); exit(-1); } aud_fx->COMB4->CombBuff21 = calloc(aud_fx->COMB4->buff_size2, sizeof(sample_t)); if(aud_fx->COMB4->CombBuff21 == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (CombFilter4): %s\n", strerror(errno)); exit(-1); } aud_fx->COMB4->CombBuff31 = calloc(aud_fx->COMB4->buff_size3, sizeof(sample_t)); if(aud_fx->COMB4->CombBuff31 == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (CombFilter4): %s\n", strerror(errno)); exit(-1); } aud_fx->COMB4->CombBuff41 = calloc(aud_fx->COMB4->buff_size4, sizeof(sample_t)); if(aud_fx->COMB4->CombBuff41 == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (CombFilter4): %s\n", strerror(errno)); exit(-1); } } } for(samp = 0; samp < audio_ctx->capture_buff_size; samp = samp + audio_ctx->channels) { sample_t out1 = in_gain * data[samp] + gain1 * aud_fx->COMB4->CombBuff10[aud_fx->COMB4->CombIndex1]; sample_t out2 = in_gain * data[samp] + gain2 * aud_fx->COMB4->CombBuff20[aud_fx->COMB4->CombIndex2]; sample_t out3 = in_gain * data[samp] + gain3 * aud_fx->COMB4->CombBuff30[aud_fx->COMB4->CombIndex3]; sample_t out4 = in_gain * data[samp] + gain4 * aud_fx->COMB4->CombBuff40[aud_fx->COMB4->CombIndex4]; aud_fx->COMB4->CombBuff10[aud_fx->COMB4->CombIndex1] = data[samp] + gain1 * aud_fx->COMB4->CombBuff10[aud_fx->COMB4->CombIndex1]; aud_fx->COMB4->CombBuff20[aud_fx->COMB4->CombIndex2] = data[samp] + gain2 * aud_fx->COMB4->CombBuff20[aud_fx->COMB4->CombIndex2]; aud_fx->COMB4->CombBuff30[aud_fx->COMB4->CombIndex3] = data[samp] + gain3 * aud_fx->COMB4->CombBuff30[aud_fx->COMB4->CombIndex3]; aud_fx->COMB4->CombBuff40[aud_fx->COMB4->CombIndex4] = data[samp] + gain4 * aud_fx->COMB4->CombBuff40[aud_fx->COMB4->CombIndex4]; data[samp] = clip_float(out1 + out2 + out3 + out4); /*if stereo process second channel */ if(audio_ctx->channels > 1) { out1 = in_gain * data[samp+1] + gain1 * aud_fx->COMB4->CombBuff11[aud_fx->COMB4->CombIndex1]; out2 = in_gain * data[samp+1] + gain2 * aud_fx->COMB4->CombBuff21[aud_fx->COMB4->CombIndex2]; out3 = in_gain * data[samp+1] + gain3 * aud_fx->COMB4->CombBuff31[aud_fx->COMB4->CombIndex3]; out4 = in_gain * data[samp+1] + gain4 * aud_fx->COMB4->CombBuff41[aud_fx->COMB4->CombIndex4]; aud_fx->COMB4->CombBuff11[aud_fx->COMB4->CombIndex1] = data[samp+1] + gain1 * aud_fx->COMB4->CombBuff11[aud_fx->COMB4->CombIndex1]; aud_fx->COMB4->CombBuff21[aud_fx->COMB4->CombIndex2] = data[samp+1] + gain2 * aud_fx->COMB4->CombBuff21[aud_fx->COMB4->CombIndex2]; aud_fx->COMB4->CombBuff31[aud_fx->COMB4->CombIndex3] = data[samp+1] + gain3 * aud_fx->COMB4->CombBuff31[aud_fx->COMB4->CombIndex3]; aud_fx->COMB4->CombBuff41[aud_fx->COMB4->CombIndex4] = data[samp+1] + gain4 * aud_fx->COMB4->CombBuff41[aud_fx->COMB4->CombIndex4]; data[samp+1] = clip_float(out1 + out2 + out3 + out4); } if(++(aud_fx->COMB4->CombIndex1) >= aud_fx->COMB4->buff_size1) aud_fx->COMB4->CombIndex1=0; if(++(aud_fx->COMB4->CombIndex2) >= aud_fx->COMB4->buff_size2) aud_fx->COMB4->CombIndex2=0; if(++(aud_fx->COMB4->CombIndex3) >= aud_fx->COMB4->buff_size3) aud_fx->COMB4->CombIndex3=0; if(++(aud_fx->COMB4->CombIndex4) >= aud_fx->COMB4->buff_size4) aud_fx->COMB4->CombIndex4=0; } } /* * All pass filter * args: * AP - pointer to fx_delay_data_t * Buff -pointer to sample buffer * NumSamples - number of samples in buffer * channels -number of audio channels * gain- filter gain * * asserts: * none * * returns: none */ static void all_pass (fx_delay_data_t *AP, sample_t *Buff, int NumSamples, int channels, float gain) { int samp = 0; float inv_gain = 1.0 / gain; for(samp = 0; samp < NumSamples; samp += channels) { AP->delayBuff1[AP->delayIndex] = Buff[samp] + (gain * AP->delayBuff1[AP->delayIndex]); Buff[samp] = ((AP->delayBuff1[AP->delayIndex] * (1 - gain*gain)) - Buff[samp]) * inv_gain; if(channels > 1) { AP->delayBuff2[AP->delayIndex] = Buff[samp+1] + (gain * AP->delayBuff2[AP->delayIndex]); Buff[samp+1] = ((AP->delayBuff2[AP->delayIndex] * (1 - gain*gain)) - Buff[samp+1]) * inv_gain; } if(++(AP->delayIndex) >= AP->buff_size) AP->delayIndex=0; } } /* * All pass for reverb * args: * audio_ctx - audio context * data - audio buffer to be processed * delay_ms - delay in ms * gain - filter gain * * asserts: * none * * returns: none */ static void all_pass1 (audio_context_t *audio_ctx, sample_t *data, int delay_ms, float gain) { if(aud_fx->AP1 == NULL) { aud_fx->AP1 = calloc(1, sizeof(fx_delay_data_t)); if(aud_fx->AP1 == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (all_pass1): %s\n", strerror(errno)); exit(-1); } aud_fx->AP1->buff_size = (int) delay_ms * (audio_ctx->samprate * 0.001); aud_fx->AP1->delayBuff1 = calloc(aud_fx->AP1->buff_size, sizeof(sample_t)); if(aud_fx->AP1->delayBuff1 == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (all_pass1): %s\n", strerror(errno)); exit(-1); } aud_fx->AP1->delayBuff2 = NULL; if(audio_ctx->channels > 1) { aud_fx->AP1->delayBuff2 = calloc(aud_fx->AP1->buff_size, sizeof(sample_t)); if(aud_fx->AP1->delayBuff2 == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (all_pass1): %s\n", strerror(errno)); exit(-1); } } } all_pass (aud_fx->AP1, data, audio_ctx->capture_buff_size, audio_ctx->channels, gain); } /* * reduce number of samples with linear interpolation * rate - rate of samples to remove [1,...[ * rate = 1-> XXX (splits channels) 2 -> X0X0X 3 -> X00X00X 4 -> X000X000X * args: * RT - pointer to fx_rate_data_t * Buff - pointer to sample buffer * rate - rate of samples to remove * NumSamples - samples in buffer * channels - audio channels * * asserts: * * returns: none */ static void change_rate_less(fx_rate_data_t *RT, sample_t *Buff, int rate, int NumSamples, int channels) { int samp = 0; int n = 0, i = 0; for (samp = 0; samp < NumSamples; samp += channels) { if (n==0) { RT->rBuff1[i] = Buff[samp]; if(channels > 1) RT->rBuff2[i] = Buff[samp + 1]; i++; } if(++n >= rate) n=0; } RT->numsamples = i; } /* * increase audio tempo by adding audio windows of wtime_ms in given rate * rate: 2 -> [w1..w2][w1..w2][w2..w3][w2..w3] 3-> [w1..w2][w1..w2][w1..w2][w2..w3][w2..w3][w2..w3] * args: * audio_ctx - audio context * data - audio buffer to be processed * rate -rate of added windows * wtime_ms - window time in ms * * asserts: * none * * returns: none */ static void change_tempo_more(audio_context_t *audio_ctx, sample_t *data, int rate, int wtime_ms) { int samp = 0; int i = 0; int r = 0; int index = 0; if(aud_fx->RT1->wBuff1 == NULL) { aud_fx->RT1->wSize = wtime_ms * audio_ctx->samprate * 0.001; aud_fx->RT1->wBuff1 = calloc(aud_fx->RT1->wSize, sizeof(sample_t)); if(aud_fx->RT1->wBuff1 == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (change_tempo_more): %s\n", strerror(errno)); exit(-1); } if (audio_ctx->channels >1) { aud_fx->RT1->wBuff2 = calloc(aud_fx->RT1->wSize, sizeof(sample_t)); if(aud_fx->RT1->wBuff2 == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (change_tempo_more): %s\n", strerror(errno)); exit(-1); } } } //printf("samples = %i\n", data->RT1->numsamples); for(samp = 0; samp < aud_fx->RT1->numsamples; samp++) { aud_fx->RT1->wBuff1[i] = aud_fx->RT1->rBuff1[samp]; if(audio_ctx->channels > 1) aud_fx->RT1->wBuff2[i] = aud_fx->RT1->rBuff2[samp]; if((++i) > aud_fx->RT1->wSize) { for (r = 0; r < rate; r++) { for(i = 0; i < aud_fx->RT1->wSize; i++) { data[index] = aud_fx->RT1->wBuff1[i]; if (audio_ctx->channels > 1) data[index +1] = aud_fx->RT1->wBuff2[i]; index += audio_ctx->channels; } } i = 0; } } } #define FUZZ(x) CubicAmplifier(CubicAmplifier(CubicAmplifier(CubicAmplifier(x)))) /* * Fuzz distortion * args: * audio_ctx - audio context * data - audio buffer to be processed * * asserts: * audio_ctx is not null * * returns: none */ static void audio_fx_fuzz (audio_context_t *audio_ctx, sample_t *data) { /*assertions*/ assert(audio_ctx != NULL); int samp=0; for(samp = 0; samp < audio_ctx->capture_buff_size; samp++) data[samp] = FUZZ(data[samp]); HPF(audio_ctx, data, 1000, 0.9); } /* * Echo effect * args: * audio_ctx - audio context * data - audio buffer to be processed * delay_ms - echo delay in ms (e.g: 300) * decay - feedback gain (<1) (e.g: 0.5) * * asserts: * audio_ctx is not null * * returns: none */ static void audio_fx_echo(audio_context_t *audio_ctx, sample_t *data, int delay_ms, float decay) { /*assertions*/ assert(audio_ctx != NULL); int samp = 0; if(aud_fx->ECHO == NULL) { aud_fx->ECHO = calloc(1, sizeof(fx_delay_data_t)); if(aud_fx->ECHO == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (audio_fx_echo): %s\n", strerror(errno)); exit(-1); } aud_fx->ECHO->buff_size = (int) delay_ms * audio_ctx->samprate * 0.001; aud_fx->ECHO->delayBuff1 = calloc(aud_fx->ECHO->buff_size, sizeof(sample_t)); if(aud_fx->ECHO->delayBuff1 == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (audio_fx_echo): %s\n", strerror(errno)); exit(-1); } aud_fx->ECHO->delayBuff2 = NULL; if(audio_ctx->channels > 1) { aud_fx->ECHO->delayBuff2 = calloc(aud_fx->ECHO->buff_size, sizeof(sample_t)); if(aud_fx->ECHO->delayBuff2 == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (audio_fx_echo): %s\n", strerror(errno)); exit(-1); } } } for(samp = 0; samp < audio_ctx->capture_buff_size; samp = samp + audio_ctx->channels) { sample_t out = (0.7 * data[samp]) + (0.3 * aud_fx->ECHO->delayBuff1[aud_fx->ECHO->delayIndex]); aud_fx->ECHO->delayBuff1[aud_fx->ECHO->delayIndex] = data[samp] + (aud_fx->ECHO->delayBuff1[aud_fx->ECHO->delayIndex] * decay); data[samp] = clip_float(out); /*if stereo process second channel in separate*/ if (audio_ctx->channels > 1) { out = (0.7 * data[samp+1]) + (0.3 * aud_fx->ECHO->delayBuff2[aud_fx->ECHO->delayIndex]); aud_fx->ECHO->delayBuff2[aud_fx->ECHO->delayIndex] = data[samp] + (aud_fx->ECHO->delayBuff2[aud_fx->ECHO->delayIndex] * decay); data[samp+1] = clip_float(out); } if(++(aud_fx->ECHO->delayIndex) >= aud_fx->ECHO->buff_size) aud_fx->ECHO->delayIndex=0; } } /* * Reverb effect * args: * audio_ctx - audio context * data - audio buffer to be processed * delay_ms - reverb delay in ms * * asserts: * audio_ctx is not null * * returns: none */ static void audio_fx_reverb (audio_context_t *audio_ctx, sample_t *data, int delay_ms) { /*assertions*/ assert(audio_ctx != NULL); /*4 parallel comb filters*/ CombFilter4 (audio_ctx, data, delay_ms, delay_ms - 5, delay_ms -10, delay_ms -15, 0.55, 0.6, 0.5, 0.45, 0.7); /*all pass*/ all_pass1 (audio_ctx, data, delay_ms, 0.75); } #define lfoskipsamples 30 /* * WahWah effect * !!!!!!!!!!!!! IMPORTANT!!!!!!!!! : * depth and freqofs should be from 0(min) to 1(max) ! * res should be greater than 0 ! * args: * audio_ctx - audio context * data - audio buffer to be processed * freq - LFO frequency (1.5) * startphase - LFO startphase in RADIANS - usefull for stereo WahWah (0) * depth - Wah depth (0.7) * freqofs - Wah frequency offset (0.3) * res - Resonance (2.5) * * asserts: * audio_ctx is not null * * returns: none */ static void audio_fx_wahwah (audio_context_t *audio_ctx, sample_t *data, float freq, float startphase, float depth, float freqofs, float res) { /*assertions*/ assert(audio_ctx != NULL); float frequency, omega, sn, cs, alpha; if(aud_fx->wahData == NULL) { aud_fx->wahData = calloc(1, sizeof(fx_wah_data_t)); if(aud_fx->wahData == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (audio_fx_wahwah): %s\n", strerror(errno)); exit(-1); } aud_fx->wahData->lfoskip = freq * 2 * M_PI / audio_ctx->samprate; aud_fx->wahData->phase = startphase; /*if right channel set: phase += (float)M_PI;*/ } int samp = 0; for(samp = 0; samp < audio_ctx->capture_buff_size; samp++) { float in = data[samp]; if ((aud_fx->wahData->skipcount++) % lfoskipsamples == 0) { frequency = (1 + cos(aud_fx->wahData->skipcount * aud_fx->wahData->lfoskip + aud_fx->wahData->phase)) * 0.5; frequency = frequency * depth * (1 - freqofs) + freqofs; frequency = exp((frequency - 1) * 6); omega = M_PI * frequency; sn = sin(omega); cs = cos(omega); alpha = sn / (2 * res); aud_fx->wahData->b0 = (1 - cs) * 0.5; aud_fx->wahData->b1 = 1 - cs; aud_fx->wahData->b2 = (1 - cs) * 0.5; aud_fx->wahData->a0 = 1 + alpha; aud_fx->wahData->a1 = -2 * cs; aud_fx->wahData->a2 = 1 - alpha; } float out = (aud_fx->wahData->b0 * in + aud_fx->wahData->b1 * aud_fx->wahData->xn1 + aud_fx->wahData->b2 * aud_fx->wahData->xn2 - aud_fx->wahData->a1 * aud_fx->wahData->yn1 - aud_fx->wahData->a2 * aud_fx->wahData->yn2) / aud_fx->wahData->a0; aud_fx->wahData->xn2 = aud_fx->wahData->xn1; aud_fx->wahData->xn1 = in; aud_fx->wahData->yn2 = aud_fx->wahData->yn1; aud_fx->wahData->yn1 = out; data[samp] = clip_float(out); } } /* * change pitch effect * args: * audio_ctx - audio context * data - audio buffer to be processed * rate - window rate * * asserts: * audio_ctx is not null * * returns: none */ static void audio_fx_change_pitch (audio_context_t *audio_ctx, sample_t *data, int rate) { if(aud_fx->RT1 == NULL) { aud_fx->RT1 = calloc(1, sizeof(fx_rate_data_t)); if(aud_fx->RT1 == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (audio_fx_change_pitch): %s\n", strerror(errno)); exit(-1); } aud_fx->RT1->wBuff1 = NULL; aud_fx->RT1->wBuff2 = NULL; aud_fx->RT1->rBuff1 = calloc(audio_ctx->capture_buff_size/audio_ctx->channels, sizeof(sample_t)); if(aud_fx->RT1->rBuff1 == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (audio_fx_change_pitch): %s\n", strerror(errno)); exit(-1); } aud_fx->RT1->rBuff2 = NULL; if(audio_ctx->channels > 1) { aud_fx->RT1->rBuff2 = calloc(audio_ctx->capture_buff_size/audio_ctx->channels, sizeof(sample_t)); if(aud_fx->RT1->rBuff2 == NULL) { fprintf(stderr,"AUDIO: FATAL memory allocation failure (audio_fx_change_pitch): %s\n", strerror(errno)); exit(-1); } } } change_rate_less(aud_fx->RT1, data, rate, audio_ctx->capture_buff_size, audio_ctx->channels); change_tempo_more(audio_ctx, data, rate, 20); LPF(audio_ctx, data, audio_ctx->samprate * 0.25, 0.9); } /* * clean fx_delay_data_t * args: * DELAY - pointer to fx_delay_data_t * * asserts: * none * * returns: none */ static void close_DELAY(fx_delay_data_t *DELAY) { if(DELAY != NULL) { free(DELAY->delayBuff1); free(DELAY->delayBuff2); free(DELAY); } } /* * clean fx_comb4_data_t * args: * COMB4 - pointer to fx_comb4_data_t * * asserts: * none * * returns: none */ static void close_COMB4(fx_comb4_data_t *COMB4) { if(COMB4 != NULL) { free(COMB4->CombBuff10); free(COMB4->CombBuff20); free(COMB4->CombBuff30); free(COMB4->CombBuff40); free(COMB4->CombBuff11); free(COMB4->CombBuff21); free(COMB4->CombBuff31); free(COMB4->CombBuff41); free(COMB4); } } /* * clean fx_filt_data_t * args: * FILT - pointer to fx_filt_data_t * * asserts: * none * * returns: none */ static void close_FILT(fx_filt_data_t *FILT) { if(FILT != NULL) { free(FILT); } } /* * clean fx_wah_data_t * args: * WAH - pointer to fx_wah_data_t * * asserts: * none * * returns: none */ static void close_WAHWAH(fx_wah_data_t *WAH) { if(WAH != NULL) { free(WAH); } } /* * clean reverb data * args: * none * * asserts: * none * * returns: none */ static void close_reverb() { close_DELAY(aud_fx->AP1); aud_fx->AP1 = NULL; close_COMB4(aud_fx->COMB4); aud_fx->COMB4 = NULL; } /* * clean pitch data * args: * none * * asserts: * none * * returns: none */ static void close_pitch () { if(aud_fx->RT1 != NULL) { free(aud_fx->RT1->rBuff1); free(aud_fx->RT1->rBuff2); free(aud_fx->RT1->wBuff1); free(aud_fx->RT1->wBuff2); free(aud_fx->RT1); aud_fx->RT1 = NULL; close_FILT(aud_fx->LPF1); aud_fx->LPF1 = NULL; } } /* * clean audio fx data * args: * none * * asserts: * none * * returns: none */ void audio_fx_close() { if(aud_fx == NULL) return; close_DELAY(aud_fx->ECHO); aud_fx->ECHO = NULL; close_reverb(); close_WAHWAH(aud_fx->wahData); aud_fx->wahData = NULL; close_FILT(aud_fx->HPF); aud_fx->HPF = NULL; close_pitch(); free(aud_fx); aud_fx = NULL; } /* * apply audio fx * args: * audio_ctx - pointer to audio context * proc_buff - pointer to audio buffer to process * mask - or'ed fx combination * * asserts: * none * * returns: none */ void audio_fx_apply(audio_context_t *audio_ctx, sample_t *data, uint32_t mask) { if(mask != AUDIO_FX_NONE) { if(verbosity > 2) printf("AUDIO: Apllying Fx (0x%x)\n", mask); if(aud_fx == NULL) audio_fx_init(); if(mask & AUDIO_FX_ECHO) audio_fx_echo(audio_ctx, data, 300, 0.5); else { close_DELAY(aud_fx->ECHO); aud_fx->ECHO = NULL; } if(mask & AUDIO_FX_REVERB) audio_fx_reverb(audio_ctx, data, 50); else close_reverb(); if(mask & AUDIO_FX_FUZZ) audio_fx_fuzz(audio_ctx, data); else { close_FILT(aud_fx->HPF); aud_fx->HPF = NULL; } if(mask & AUDIO_FX_WAHWAH) audio_fx_wahwah(audio_ctx, data, 1.5, 0, 0.7, 0.3, 2.5); else { close_WAHWAH(aud_fx->wahData); aud_fx->wahData = NULL; } if(mask & AUDIO_FX_DUCKY) audio_fx_change_pitch(audio_ctx, data, 2); else close_pitch(); } else audio_fx_close(); }
30,637
C
.c
1,089
25.637282
111
0.626922
linuxdeepin/dtkmultimedia
3
16
2
LGPL-3.0
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
15,285,535
gui.c
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam_v4l2core/gui.c
/*******************************************************************************# # guvcview http://guvcview.sourceforge.net # # # # Paulo Assis <[email protected]> # # Nobuhiro Iwamatsu <[email protected]> # # Add UYVY color support(Macbook iSight) # # Flemming Frandsen <[email protected]> # # Add VU meter OSD # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 2 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program; if not, write to the Free Software # # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # ********************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <errno.h> #include <assert.h> /* support for internationalization - i18n */ #include <locale.h> #include <libintl.h> #include "core_io.h" #include "camview.h" #include "gviewencoder.h" #include "cameraconfig.h" #include "gui.h" extern int debug_level; //int is_control_panel = 0; /*default camera button action: DEF_ACTION_IMAGE - save image; DEF_ACTION_VIDEO - save video*/ __attribute__((unused))static int default_camera_button_action = 0; /*photo basename*/ static char *photo_name = NULL; /*photo path*/ static char *photo_path = NULL; /*photo format*/ static int photo_format = IMG_FMT_JPG; /*video basename*/ static char *video_name = NULL; /*video path*/ static char *video_path = NULL; /*video format*/ static int video_muxer = ENCODER_MUX_WEBM; /*index: 0 numerator; 1 denominator*/ static int my_fps[2] = {0, 0}; /* * gets the current video codec index * args: * none * * asserts: * none * * returns: current codec index */ int get_video_codec_ind() { return my_video_codec_ind; } /* * sets the current video codec index * args: * index - codec index * * asserts: * none * * returns: none */ void set_video_codec_ind(int index) { my_video_codec_ind = index; /*update config*/ config_t *my_config = config_get(); if(index == 0) strncpy(my_config->video_codec, "raw", 4); else { const char *codec_4cc = encoder_get_video_codec_4cc(index); if(codec_4cc) { strncpy(my_config->video_codec, codec_4cc, 4); lowercase(my_config->video_codec); } } } /* * gets the current audio codec index * args: * none * * asserts: * none * * returns: current codec index */ int get_audio_codec_ind() { return my_audio_codec_ind; } /* * sets the current audio codec index * args: * index - codec index * * asserts: * none * * returns: none */ void set_audio_codec_ind(int index) { my_audio_codec_ind = index; /*update config*/ config_t *my_config = config_get(); const char *codec_name = encoder_get_audio_codec_name(index); if(codec_name) { strncpy(my_config->audio_codec, codec_name, 4); lowercase(my_config->video_codec); } } /* * gets the current fps numerator * args: * none * * asserts: * none * * returns: current fps numerator */ //int gui_get_fps_num() //{ // return my_fps[0]; //} /* * gets the current fps denominator * args: * none * * asserts: * none * * returns: current fps denominator */ //int gui_get_fps_denom() //{ // return my_fps[1]; //} /* * stores the fps * args: * fps - array with fps numerator and denominator * * asserts: * none * * returns: none */ void gui_set_fps(int fps[2]) { my_fps[0] = fps[0]; my_fps[1] = fps[1]; /*update config*/ config_t *my_config = config_get(); my_config->fps_num = my_fps[0]; my_config->fps_denom = my_fps[1]; } /* * gets the control profile file name * args: * none * * asserts: * none * * returns: control profile file name */ char *get_profile_name() { if(!profile_name) profile_name = strdup("default.gpfl"); return profile_name; } /* * sets the device name * args: * name: device name * * asserts: * none * * returns: none */ void set_device_location(const char *name) { if(device_location != NULL) free(device_location); device_location = strdup(name); /* update the config */ config_t *my_config = config_get(); /*this can be the function arg 'name'*/ if(my_config->device_location) free(my_config->device_location); /*so here we use the dup string*/ my_config->device_location = strdup(device_location); } /* * sets the device name * args: * name: device name * * asserts: * none * * returns: none */ void set_device_name(const char *name) { if(device_name != NULL) free(device_name); /* update the config */ config_t *my_config = config_get(); if(name == NULL) { device_name = strdup(my_config->device_name); } else { device_name = strdup(name); } /*this can be the function arg 'name'*/ if(my_config->device_name) free(my_config->device_name); /*so here we use the dup string*/ my_config->device_name = strdup(device_name); } char* get_device_name(void) { if(!device_name) device_name = strdup("none"); return device_name; } /* * sets the control profile file name * args: * name: control profile file name * * asserts: * none * * returns: none */ void set_profile_name(const char *name) { if(profile_name != NULL) free(profile_name); profile_name = strdup(name); /* update the config */ config_t *my_config = config_get(); /*this can be the function arg 'name'*/ if(my_config->profile_name) free(my_config->profile_name); /*so here we use the dup string*/ my_config->profile_name = strdup(profile_name); } /* * gets the control profile path (to dir) * args: * none * * asserts: * none * * returns: control profile file path */ char *get_profile_path() { if(!profile_path) profile_path = strdup(getenv("HOME")); return profile_path; } /* * sets the control profile path (to dir) * args: * path: control profile path * * asserts: * none * * returns: none */ void set_profile_path(const char *path) { if(profile_path != NULL) free(profile_path); profile_path = strdup(path); /* update the config */ config_t *my_config = config_get(); /*this can be the function arg 'path'*/ if(my_config->profile_path) free(my_config->profile_path); /*so here we use the dup string*/ my_config->profile_path = strdup(profile_path); } /* * gets video sufix flag * args: * none * * asserts: * none * * returns: video sufix flag */ int get_video_sufix_flag() { return video_sufix_flag; } /* * sets the video sufix flag * args: * flag: video sufix flag * * asserts: * none * * returns: none */ void set_video_sufix_flag(int flag) { video_sufix_flag = flag; } /* * gets video muxer * args: * none * * asserts: * none * * returns: video muxer */ int get_video_muxer() { return video_muxer; } /* * sets video muxer * args: * muxer - video muxer (ENCODER_MUX_[MKV|WEBM|AVI]) * * asserts: * none * * returns: none */ void set_video_muxer(int muxer) { video_muxer = muxer; } /* * gets the video file basename * args: * none * * asserts: * none * * returns: video file basename */ char *get_video_name() { if(!video_name) video_name = strdup(""); return video_name; } /* * sets the video file basename * args: * name: video file basename * * asserts: * none * * returns: none */ void set_video_name(const char *name) { if(video_name != NULL) free(video_name); video_name = strdup(name); /*get image format*/ char *ext = get_file_extension(name); if(ext == NULL) { if(video_name) free(video_name); fprintf(stderr, "deepin-camera: no valid file extension for video file %s\n", name); fprintf(stderr, "deepin-camera: using muxer %i\n", get_video_muxer()); switch(get_video_muxer()) { case ENCODER_MUX_MKV: video_name = set_file_extension(name, "mkv"); break; case ENCODER_MUX_WEBM: video_name = set_file_extension(name, "webm"); break; case ENCODER_MUX_MP4: video_name = set_file_extension(name,"mp4"); break; default: video_name = set_file_extension(name, "avi"); break; } } else if( strcasecmp(ext, "mkv") == 0) set_video_muxer(ENCODER_MUX_MKV); else if(strcasecmp(ext,"mp4") == 0) { video_codec_t *codec = encoder_get_video_codec_defaults(encoder_get_video_codec_ind_4cc("H264")); int video_codec_ind = get_video_codec_list_index(codec->codec_id); set_video_codec_ind(video_codec_ind); set_audio_codec_ind(encoder_get_audio_codec_ind_name("AAC")); set_video_muxer(ENCODER_MUX_MP4); } else if ( strcasecmp(ext, "webm") == 0 ) { set_video_muxer(ENCODER_MUX_WEBM); //注释这个地方是因为占用CPU过高 /*force webm codecs*/ int video_codec_ind = encoder_get_webm_video_codec_index(); set_video_codec_ind(video_codec_ind); int audio_codec_ind = encoder_get_webm_audio_codec_index(); set_audio_codec_ind(audio_codec_ind); } else if ( strcasecmp(ext, "avi") == 0 ) set_video_muxer(ENCODER_MUX_AVI); if(ext) free(ext); /* update the config */ config_t *my_config = config_get(); /*this can be the function arg 'name'*/ if(my_config->video_name) free(my_config->video_name); /*so here we use the dup string*/ my_config->video_name = strdup(video_name); } /* * gets the video file path (to dir) * args: * none * * asserts: * none * * returns: video file path */ char *get_video_path() { if(!video_path) video_path = strdup(getenv("HOME")); if(access(video_path,F_OK&W_OK) < 0) { char* str = getenv("HOME"); if(strstr(str, "/Videos") == NULL) strcat(str, "/Videos"); video_path = (char*)malloc(sizeof(str)); strcpy(video_path, str); } return video_path; } /* * sets video path (to dir) * args: * path: video file path * * asserts: * none * * returns: none */ void set_video_path(const char *path) { if(video_path != NULL) free(video_path); video_path = strdup(path); if(access(video_path, 0) != 0) { video_path = getenv("HOME"); strcat(video_path,"/Videos"); } /* update the config */ config_t *my_config = config_get(); /*this can be the function arg 'path'*/ if(my_config->video_path) free(my_config->video_path); /*so here we use the dup string*/ my_config->video_path = strdup(video_path); } /* * gets photo sufix flag * args: * none * * asserts: * none * * returns: photo sufix flag */ int get_photo_sufix_flag() { return photo_sufix_flag; } /* * sets the photo sufix flag * args: * flag: photo sufix flag * * asserts: * none * * returns: none */ void set_photo_sufix_flag(int flag) { photo_sufix_flag = flag; } /* * gets photo format * args: * none * * asserts: * none * * returns: photo format */ int get_photo_format() { return photo_format; } /* * sets photo format * args: * format - photo format (IMG_FMT_[JPG|BMP|PNG|RAW]) * * asserts: * none * * returns: none */ void set_photo_format(int format) { photo_format = format; } /* * gets the photo file basename * args: * none * * asserts: * none * * returns: photo file basename */ char *get_photo_name() { if(!photo_name) photo_name = strdup("my_photo.jpg"); return photo_name; } /* * sets the photo file basename and image format * args: * name: photo file basename * * asserts: * none * * returns: none */ void set_photo_name(const char *name) { if(photo_name) free(photo_name); photo_name = strdup(name); /*get image format*/ char *ext = get_file_extension(name); if(ext == NULL) { if(photo_name) free(photo_name); fprintf(stderr, "deepin-camera: no valid file extension for image file %s\n", name); fprintf(stderr, "deepin-camera: using format %i\n", get_photo_format()); switch(get_photo_format()) { case IMG_FMT_JPG: photo_name = set_file_extension(name, "jpg"); break; case IMG_FMT_PNG: photo_name = set_file_extension(name, "png"); break; case IMG_FMT_BMP: photo_name = set_file_extension(name, "bmp"); break; default: photo_name = set_file_extension(name, "raw"); break; } } else if( strcasecmp(ext, "jpg") == 0 || strcasecmp(ext, "jpeg") == 0 ) set_photo_format(IMG_FMT_JPG); else if ( strcasecmp(ext, "png") == 0 ) set_photo_format(IMG_FMT_PNG); else if ( strcasecmp(ext, "bmp") == 0 ) set_photo_format(IMG_FMT_BMP); else if ( strcasecmp(ext, "raw") == 0 ) set_photo_format(IMG_FMT_RAW); if(ext) free(ext); /*update the config*/ config_t *my_config = config_get(); /*this can be the function arg 'name'*/ if(my_config->photo_name) free(my_config->photo_name); /*so here we use the dup string*/ my_config->photo_name = strdup(photo_name); } /* * gets the photo file path (to dir) * args: * none * * asserts: * none * * returns: photo file path */ char *get_photo_path() { if(!photo_path) photo_path = strdup(getenv("HOME")); return photo_path; } /* * sets photo path (to dir) * args: * path: photo file path * * asserts: * none * * returns: none */ void set_photo_path(const char *path) { if(photo_path != NULL) free(photo_path); photo_path = strdup(path); /*update the config*/ config_t *my_config = config_get(); /*this can be the function arg 'path'*/ if(my_config->photo_path) free(my_config->photo_path); /*so here we use the dup string*/ my_config->photo_path = strdup(photo_path); }
14,963
C
.c
682
19.343109
109
0.612771
linuxdeepin/dtkmultimedia
3
16
2
LGPL-3.0
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,285,542
save_image_bmp.c
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam_v4l2core/save_image_bmp.c
/*******************************************************************************# # guvcview http://guvcview.sourceforge.net # # # # Paulo Assis <[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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # ********************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <inttypes.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <errno.h> #include <assert.h> #include "gviewv4l2core.h" #include "save_image.h" #include "colorspaces.h" #include "cameraconfig.h" typedef struct _bmp_file_header_t { uint16_t bfType; //Specifies the file type, must be BM uint32_t bfSize; //Specifies the size, in bytes, of the bitmap file uint16_t bfReserved1; //Reserved; must be zero uint16_t bfReserved2; //Reserved; must be zero uint32_t bfOffBits; /*Specifies the offset, in bytes, from the beginning of the BITMAPFILEHEADER structure to the bitmap bits= FileHeader+InfoHeader+RGBQUAD(0 for 24bit BMP)=64*/ } __attribute__ ((packed)) bmp_file_header_t; typedef struct _bmp_info_header_t { uint32_t biSize; /*size of this header 40 bytes*/ int32_t biWidth; int32_t biHeight; uint16_t biPlanes; /*color planes - set to 1*/ uint16_t biBitCount; /*bits per pixel - color depth (use 24)*/ uint32_t biCompression; /*BI_RGB = 0*/ uint32_t biSizeImage; uint32_t biXPelsPerMeter; uint32_t biYPelsPerMeter; uint32_t biClrUsed; uint32_t biClrImportant; } __attribute__ ((packed)) bmp_info_header_t; /* * save bmp data to file * args: * filename - bmp file name * data - pixel data (rgb form) * width - image width * height - image height * BitCount - bits per pixel * * asserts: * data is not null * * returns: error code */ static int save_bmp(const char *filename, uint8_t *data, int width, int height, int BitCount) { /*assertions*/ assert(data != NULL); int ret = E_OK; bmp_file_header_t BmpFileh; bmp_info_header_t BmpInfoh; FILE *fp; int imgsize = width * height * BitCount / 8; BmpFileh.bfType=0x4d42;//must be BM (x4d42) /*Specifies the size, in bytes, of the bitmap file*/ BmpFileh.bfSize=sizeof(bmp_file_header_t)+sizeof(bmp_info_header_t)+imgsize; BmpFileh.bfReserved1=0; //Reserved; must be zero BmpFileh.bfReserved2=0; //Reserved; must be zero /*Specifies the offset, in bytes, */ /*from the beginning of the BITMAPFILEHEADER structure */ /* to the bitmap bits */ BmpFileh.bfOffBits=sizeof(bmp_file_header_t)+sizeof(bmp_info_header_t); BmpInfoh.biSize=40; BmpInfoh.biWidth=width; BmpInfoh.biHeight=height; BmpInfoh.biPlanes=1; BmpInfoh.biBitCount=BitCount; BmpInfoh.biCompression=0; // 0 BmpInfoh.biSizeImage=imgsize; BmpInfoh.biXPelsPerMeter=0; BmpInfoh.biYPelsPerMeter=0; BmpInfoh.biClrUsed=0; BmpInfoh.biClrImportant=0; if ((fp = fopen(filename, "wb")) != NULL) { // (wb) write in binary mode ret=fwrite(&BmpFileh, sizeof(bmp_file_header_t), 1, fp); ret+=fwrite(&BmpInfoh, sizeof(bmp_info_header_t),1,fp); ret+=fwrite(data, imgsize, 1, fp); if (ret < 3) ret = E_FILE_IO_ERR;//write error else ret = E_OK; fflush(fp); //flush data stream to file system if(fsync(fileno(fp)) || fclose(fp)) { fprintf(stderr, "V4L2_CORE: (save bmp) couldn't write to file %s: %s\n", filename, strerror(errno)); ret = E_FILE_IO_ERR; } } else { ret=1; fprintf(stderr, "V4L2_CORE: (save bmp) could not open file %s for write \n", filename); } return ret; } /* * save frame data to a bmp file * args: * frame - pointer to frame buffer * filename - filename string * * asserts: * none * * returns: error code */ int save_image_bmp(v4l2_frame_buff_t *frame, const char *filename) { int ret = E_OK; int width = frame->width; int height = frame->height; uint8_t *bmp = calloc(width * height * 3, sizeof(uint8_t)); if(bmp == NULL) { fprintf(stderr, "V4L2_CORE: FATAL memory allocation failure (save_img_bmp): %s\n", strerror(errno)); exit(-1); } yu12_to_dib24(bmp, frame->yuv_frame, width, height); ret = save_bmp(filename, bmp, width, height, 24); free(bmp); return ret; }
5,580
C
.c
152
34.651316
102
0.595933
linuxdeepin/dtkmultimedia
3
16
2
LGPL-3.0
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
15,285,543
v4l2_controls.c
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam_v4l2core/v4l2_controls.c
/*******************************************************************************# # guvcview http://guvcview.sourceforge.net # # # # Paulo Assis <[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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # ********************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <linux/videodev2.h> #include <fcntl.h> #include <string.h> #include <sys/ioctl.h> #include <libv4l2.h> #include <errno.h> #include <assert.h> /* support for internationalization - i18n */ #include <locale.h> #include <libintl.h> #include "gviewv4l2core.h" #include "v4l2_devices.h" #include "v4l2_controls.h" #include "v4l2_xu_ctrls.h" #include "cameraconfig.h" #include "load_libs.h" #ifndef V4L2_CTRL_ID2CLASS #define V4L2_CTRL_ID2CLASS(id) ((id) & 0x0fff0000UL) #endif extern int verbosity; // GUID for logitech peripheral (pan/tilt) V3 extension unit: {FFE52D21-8030-4E2C-82d9-f587d00540bd} #define GUID_LOGITECH_PERIPHERAL_XU {0x21, 0x2D, 0xE5, 0xFF, 0x30, 0x80, 0x2C, 0x4E, 0x82, 0xD9, 0xF5, 0x87, 0xD0, 0x05, 0x40, 0xBD} /* * needed only for language files (not used) */ /* V4L2 control strings */ #define CSTR_USER_CLASS N_("User Controls") #define CSTR_BRIGHT N_("Brightness") #define CSTR_CONTRAST N_("Contrast") #define CSTR_HUE N_("Hue") #define CSTR_SATURAT N_("Saturation") #define CSTR_SHARP N_("Sharpness") #define CSTR_GAMMA N_("Gamma") #define CSTR_BLCOMP N_("Backlight Compensation") #define CSTR_PLFREQ N_("Power Line Frequency") #define CSTR_HUEAUTO N_("Hue, Automatic") #define CSTR_FOCUSAUTO N_("Focus, Auto") #define CSTR_EXPMENU1 N_("Manual Mode") #define CSTR_EXPMENU2 N_("Auto Mode") #define CSTR_EXPMENU3 N_("Shutter Priority Mode") #define CSTR_EXPMENU4 N_("Aperture Priority Mode") #define CSTR_BLACK_LEVEL N_("Black Level") #define CSTR_AUTO_WB N_("White Balance, Automatic") #define CSTR_DO_WB N_("Do White Balance") #define CSTR_RB N_("Red Balance") #define CSTR_BB N_("Blue Balance") #define CSTR_EXP N_("Exposure") #define CSTR_AUTOGAIN N_("Gain, Automatic") #define CSTR_GAIN N_("Gain") #define CSTR_HFLIP N_("Horizontal Flip") #define CSTR_VFLIP N_("Vertical Flip") #define CSTR_HCENTER N_("Horizontal Center") #define CSTR_VCENTER N_("Vertical Center") #define CSTR_CHR_AGC N_("Chroma AGC") #define CSTR_CLR_KILL N_("Color Killer") #define CSTR_COLORFX N_("Color Effects") /* CAMERA CLASS control strings */ #define CSTR_CAMERA_CLASS N_("Camera Controls") #define CSTR_EXPAUTO N_("Auto Exposure") #define CSTR_EXPABS N_("Exposure Time, Absolute") #define CSTR_EXPAUTOPRI N_("Exposure, Dynamic Framerate") #define CSTR_PAN_REL N_("Pan, Relative") #define CSTR_TILT_REL N_("Tilt, Relative") #define CSTR_PAN_RESET N_("Pan, Reset") #define CSTR_TILT_RESET N_("Tilt, Reset") #define CSTR_PAN_ABS N_("Pan, Absolute") #define CSTR_TILT_ABS N_"Tilt, Absolute") #define CSTR_FOCUS_ABS N_("Focus, Absolute") #define CSTR_FOCUS_REL N_("Focus, Relative") #define CSTR_FOCUS_AUTO N_("Focus, Automatic") #define CSTR_ZOOM_ABS N_("Zoom, Absolute") #define CSTR_ZOOM_REL N_("Zoom, Relative") #define CSTR_ZOOM_CONT N_("Zoom, Continuous") #define CSTR_PRIV N_("Privacy") /* UVC specific control strings */ #define CSTR_EXPAUTO_UVC N_("Exposure, Auto") #define CSTR_EXPAUTOPRI_UVC N_("Exposure, Auto Priority") #define CSTR_EXPABS_UVC N_("Exposure (Absolute)") #define CSTR_WBTAUTO_UVC N_("White Balance Temperature, Auto") #define CSTR_WBT_UVC N_("White Balance Temperature") #define CSTR_WBCAUTO_UVC N_("White Balance Component, Auto") #define CSTR_WBCB_UVC N_("White Balance Blue Component") #define CSTR_WBCR_UVC N_("White Balance Red Component") /* libwebcam specific control strings */ #define CSTR_FOCUS_LIBWC N_("Focus") #define CSTR_FOCUSABS_LIBWC N_("Focus (Absolute)") /* * don't use xioctl for control query when using V4L2_CTRL_FLAG_NEXT_CTRL * args: * vd - pointer to video device data * current_ctrl - current control id * ctrl - pointer to v4l2_queryctrl data * * asserts: * vd is not null * vd->fd is valid ( > 0 ) * ctrl is not null * * returns: error code */ static int query_ioctl(v4l2_dev_t *vd, int current_ctrl, struct v4l2_queryctrl* ctrl) { /*assertions*/ assert(vd != NULL); assert(vd->fd > 0); assert(ctrl != NULL); int ret = 0; int tries = 4; do { if(ret) ctrl->id = (__u32)current_ctrl | V4L2_CTRL_FLAG_NEXT_CTRL; ret = getV4l2()->m_v4l2_ioctl(vd->fd, VIDIOC_QUERYCTRL, ctrl); } while (ret && tries-- && ((errno == EIO || errno == EPIPE || errno == ETIMEDOUT))); return(ret); } /* * output control data * args: * control - pointer to control data * i - control index (from control list) * * asserts: * none * * returns: void */ static void print_control(v4l2_ctrl_t *control, int i) { if(control == NULL) { printf("V4L2_CORE: null control at index %i\n", i); return; } int j=0; switch (control->control.type) { case V4L2_CTRL_TYPE_INTEGER: printf("control[%d]:(int) 0x%x '%s'\n",i ,control->control.id, control->name); printf("\tmin:%d max:%d step:%d def:%d curr:%d\n", control->control.minimum, control->control.maximum, control->control.step, control->control.default_value, control->value); free(control->name); control->name=NULL; break; case V4L2_CTRL_TYPE_INTEGER64: printf("control[%d]:(int64) 0x%x '%s'\n",i ,control->control.id, control->name); printf ("\tcurr:%" PRId64 "\n", control->value64); free(control->name); control->name=NULL; break; case V4L2_CTRL_TYPE_STRING: printf("control[%d]:(str) 0x%x '%s'\n",i ,control->control.id, control->name); printf ("\tmin:%d max:%d step:%d curr: %s\n", control->control.minimum, control->control.maximum, control->control.step, control->string); free(control->name); control->name=NULL; break; case V4L2_CTRL_TYPE_BOOLEAN: printf("control[%d]:(bool) 0x%x '%s'\n",i ,control->control.id, control->name); printf ("\tdef:%d curr:%d\n", control->control.default_value, control->value); free(control->name); control->name=NULL; break; case V4L2_CTRL_TYPE_MENU: printf("control[%d]:(menu) 0x%x '%s'\n",i ,control->control.id, control->name); printf("\tmin:%d max:%d def:%d curr:%d\n", control->control.minimum, control->control.maximum, control->control.default_value, control->value); for (j = 0; (__s32)control->menu[j].index <= control->control.maximum; j++) printf("\tmenu[%d]: [%d] -> '%s'\n", j, control->menu[j].index, control->menu_entry[j]); free(control->name); control->name=NULL; break; case V4L2_CTRL_TYPE_INTEGER_MENU: printf("control[%d]:(intmenu) 0x%x '%s'\n",i ,control->control.id, control->name); printf("\tmin:%d max:%d def:%d curr:%d\n", control->control.minimum, control->control.maximum, control->control.default_value, control->value); for (j = 0; (__s32)control->menu[j].index <= control->control.maximum; j++) printf("\tmenu[%d]: [%d] -> %" PRId64 " (0x%" PRIx64 ")\n", j, control->menu[j].index, (int64_t) control->menu[j].value, (int64_t) control->menu[j].value); free(control->name); control->name=NULL; break; case V4L2_CTRL_TYPE_BUTTON: printf("control[%d]:(button) 0x%x '%s'\n",i ,control->control.id, control->name); free(control->name); control->name=NULL; break; case V4L2_CTRL_TYPE_BITMASK: //LMH0613减去这2条有警告的打印信息 // printf("control[%d]:(bitmask) 0x%x '%s'\n",i ,control->control.id, control->name); // printf("\tmin:%x max:%x def:%x curr:%x\n", // control->control.minimum, control->control.maximum, // control->control.default_value, control->value); default: printf("control[%d]:(unknown - 0x%x) 0x%x '%s'\n",i ,control->control.type, control->control.id, control->control.name); free(control->name); control->name=NULL; break; } } /* * prints control list to stdout * args: * vd - pointer to video device data * * asserts: * vd is not null * * returns: void */ static void print_control_list(v4l2_dev_t *vd) { /*asserts*/ assert(vd != NULL); if(vd->list_device_controls == NULL) { printf("V4L2_CORE: WARNING empty control list\n"); return; } int i = 0; v4l2_ctrl_t *current = vd->list_device_controls; for(; current != NULL; current = current->next) { print_control(current, i); i++; } } /* * gets the logitech peripheral (pan/tilt) V3 xu control unit id, if any * args: * vd - pointer to video device data * * asserts: * none * * returns: unit id or 0 if none */ static uint8_t get_logitech_peripheral_unit_id (v4l2_dev_t *vd) { if(verbosity > 1) printf("V4L2_CORE: checking for logitech peripheral unit id\n"); uint8_t guid[16] = GUID_LOGITECH_PERIPHERAL_XU; return get_guid_unit_id (vd, guid); } /* * subscribe for v4l2 control events * args: * vd - pointer to video device data * control_id - id of control to subscribe events for * * asserts: * vd is not null * * return: none */ void v4l2_subscribe_control_events(v4l2_dev_t *vd, unsigned int control_id) { vd->evsub.type = V4L2_EVENT_CTRL; vd->evsub.id = control_id; int ret = xioctl(vd->fd, VIDIOC_SUBSCRIBE_EVENT, &vd->evsub); if(ret) fprintf(stderr, "V4L2_CORE: failed to subscribe events for control 0x%08x: %s\n", control_id, strerror(errno)); } /* * unsubscribev4l2 control events * args: * vd - pointer to video device data * * asserts: * vd is not null * * return: none */ void v4l2_unsubscribe_control_events(v4l2_dev_t *vd) { vd->evsub.type = V4L2_EVENT_ALL; vd->evsub.id = 0; int ret = xioctl(vd->fd, VIDIOC_UNSUBSCRIBE_EVENT, &vd->evsub); if(ret) fprintf(stderr, "V4L2_CORE: failed to unsubscribe events: %s\n", strerror(errno)); } /* * add control to control list * args: * vd - pointer to video device data * queryctrl - pointer to v4l2_queryctrl data * current - pointer to pointer of current control from control list * first - pointer to pointer of first control from control list * * asserts: * vd is not null * vd->fd is valid * queryctrl is not null * * returns: pointer to newly added control */ static v4l2_ctrl_t *add_control(v4l2_dev_t *vd, struct v4l2_queryctrl* queryctrl, v4l2_ctrl_t **current, v4l2_ctrl_t **first) { /*assertions*/ assert(vd != NULL); assert(vd->fd > 0); assert(queryctrl != NULL); int menu_entries = 0; v4l2_ctrl_t *control = NULL; struct v4l2_querymenu* menu = NULL; //menu list struct v4l2_querymenu* old_menu = menu; //temp menu list pointer if (queryctrl->flags & V4L2_CTRL_FLAG_DISABLED) { printf("V4L2_CORE: Control 0x%08x is disabled: remove it from control list\n", queryctrl->id); return NULL; } //check menu items if needed if(queryctrl->type == V4L2_CTRL_TYPE_MENU || queryctrl->type == V4L2_CTRL_TYPE_INTEGER_MENU ) { int i = 0; struct v4l2_querymenu querymenu={0}; for (querymenu.index = (__u32)queryctrl->minimum; querymenu.index <= (__u32)queryctrl->maximum; querymenu.index++) { querymenu.id = queryctrl->id; if (xioctl (vd->fd, (int)VIDIOC_QUERYMENU, &querymenu) < 0) { continue; } old_menu = menu; if(!menu) menu = calloc((size_t)(i+1), sizeof(struct v4l2_querymenu)); else menu = realloc(menu, (size_t)(i+1) * sizeof(struct v4l2_querymenu)); if(menu == NULL) { /*since we exit on failure there was no need to free any previous */ /* menu allocation (realloc), but silence cppcheck anyway */ if(old_menu) free(old_menu); fprintf(stderr, "V4L2_CORE: FATAL memory allocation failure (add_control): %s\n", strerror(errno)); exit(-1); } memcpy(&(menu[i]), &querymenu, sizeof(struct v4l2_querymenu)); i++; } old_menu = menu; /*last entry (NULL name)*/ if(!menu) menu = calloc((size_t)(i+1), sizeof(struct v4l2_querymenu)); else menu = realloc(menu, (size_t)(i+1) * sizeof(struct v4l2_querymenu)); if(menu == NULL) { /*since we exit on failure there was no need to free any previous */ /* menu allocation (realloc), but silence cppcheck anyway */ if(old_menu) free(old_menu); fprintf(stderr, "V4L2_CORE: FATAL memory allocation failure (add_control): %s\n", strerror(errno)); exit(-1); } menu[i].id = querymenu.id; menu[i].index = (__u32)queryctrl->maximum+1; if(queryctrl->type == V4L2_CTRL_TYPE_MENU) menu[i].name[0] = 0; menu_entries = i; } /*check for focus control to enable software autofocus*/ if(queryctrl->id == V4L2_CID_FOCUS_LOGITECH || queryctrl->id == V4L2_CID_FOCUS_ABSOLUTE) vd->has_focus_control_id = (int)queryctrl->id; /*check for pan/tilt control*/ else if(queryctrl->id == V4L2_CID_TILT_RELATIVE || queryctrl->id == V4L2_CID_PAN_RELATIVE) { /*get unit id for logitech pan_tilt V3 if any*/ vd->has_pantilt_control_id = 1; vd->pantilt_unit_id = get_logitech_peripheral_unit_id(vd); } // Add the control to the linked list control = calloc (1, sizeof(v4l2_ctrl_t)); if(control == NULL) { fprintf(stderr, "V4L2_CORE: FATAL memory allocation failure (add_control): %s\n", strerror(errno)); exit(-1); } memcpy(&(control->control), queryctrl, sizeof(struct v4l2_queryctrl)); control->cclass = V4L2_CTRL_ID2CLASS(control->control.id); control->name = dgettext(GETTEXT_PACKAGE_V4L2CORE, (char *) control->control.name); //add the menu adress (NULL if not a menu) control->menu = menu; if(control->menu != NULL && control->control.type == V4L2_CTRL_TYPE_MENU) { int i = 0; control->menu_entry = calloc((size_t)(menu_entries), sizeof(char *)); if(control->menu_entry == NULL) { fprintf(stderr, "V4L2_CORE: FATAL memory allocation failure (add_control): %s\n", strerror(errno)); exit(-1); } for(i = 0; i< menu_entries; i++) control->menu_entry[i] = strdup(dgettext(GETTEXT_PACKAGE_V4L2CORE, (char *) control->menu[i].name)); control->menu_entries = menu_entries; } else { control->menu_entries = 0; control->menu_entry = NULL; } //allocate a string with max size if needed if(control->control.type == V4L2_CTRL_TYPE_STRING) { control->string = (char *) calloc ((size_t)control->control.maximum + 1, sizeof(char)); if(control->string == NULL) { fprintf(stderr, "V4L2_CORE: FATAL memory allocation failure (add_control): %s\n", strerror(errno)); exit(-1); } } else control->string = NULL; if(*first != NULL) { (*current)->next = control; *current = control; } else { *first = control; *current = *first; } //subscribe control events v4l2_subscribe_control_events(vd, queryctrl->id); return control; } /* * enumerate device (read/write) controls * args: * vd - pointer to video device data * * asserts: * vd is not null * vd->fd is valid ( > 0 ) * vd->list_device_controls is null * * returns: error code */ int enumerate_v4l2_control(v4l2_dev_t *vd) { /*assertions*/ assert(vd != NULL); assert(vd->fd > 0); assert(vd->list_device_controls == NULL); int ret=0; v4l2_ctrl_t *current = NULL; int n = 0; struct v4l2_queryctrl queryctrl={0}; int currentctrl = 0; queryctrl.id = V4L2_CTRL_FLAG_NEXT_CTRL; /*try the next_flag method first*/ while ((ret=query_ioctl(vd, currentctrl, &queryctrl)) == 0) { if(add_control(vd, &queryctrl, &current, &(vd->list_device_controls)) != NULL) n++; currentctrl = (int)queryctrl.id; queryctrl.id |= V4L2_CTRL_FLAG_NEXT_CTRL; } if (queryctrl.id != V4L2_CTRL_FLAG_NEXT_CTRL) { vd->num_controls = n; if(verbosity > 0) print_control_list(vd); return E_OK; } if(ret) fprintf(stderr, "V4L2_CORE: Control 0x%08x failed to query with error %i\n", queryctrl.id, ret); printf("buggy V4L2_CTRL_FLAG_NEXT_CTRL flag implementation (workaround enabled)\n"); /* * next_flag method failed, loop through the ids: * * USER CLASS Controls */ for (currentctrl = V4L2_CID_USER_BASE; currentctrl < V4L2_CID_LASTP1; currentctrl++) { queryctrl.id = (__u32)currentctrl; if (xioctl(vd->fd, (int)VIDIOC_QUERYCTRL, &queryctrl) == 0) { if(add_control(vd, &queryctrl, &current, &(vd->list_device_controls)) != NULL) n++; } } /* CAMERA CLASS Controls */ for (currentctrl = V4L2_CID_CAMERA_CLASS_BASE; currentctrl < V4L2_CID_CAMERA_CLASS_BASE+32; currentctrl++) { queryctrl.id = (__u32)currentctrl; if (xioctl(vd->fd, (int)VIDIOC_QUERYCTRL, &queryctrl) == 0) { if(add_control(vd, &queryctrl, &current, &(vd->list_device_controls)) != NULL) n++; } } /* PRIVATE controls (deprecated) */ for (queryctrl.id = V4L2_CID_PRIVATE_BASE; xioctl(vd->fd, (int)VIDIOC_QUERYCTRL, &queryctrl) == 0; queryctrl.id++) { if(add_control(vd, &queryctrl, &current, &(vd->list_device_controls)) != NULL) n++; } vd->num_controls = n; if(verbosity > 0) print_control_list(vd); return E_OK; } /* * update the control flags - called when setting controls * FIXME: use control events * * args: * vd - pointer to video device data * id - control id * * asserts: * vd is not null * * returns: error code */ static void update_ctrl_flags(v4l2_dev_t *vd, int id) { /*asserts*/ assert(vd != NULL); switch (id) { case V4L2_CID_EXPOSURE_AUTO: { v4l2_ctrl_t *ctrl_this = v4l2core_get_control_by_id(vd, id); if(ctrl_this == NULL) break; switch (ctrl_this->value) { case V4L2_EXPOSURE_AUTO: { v4l2_ctrl_t *ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_IRIS_ABSOLUTE ); if (ctrl_that) ctrl_that->control.flags |= V4L2_CTRL_FLAG_GRABBED; ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_IRIS_RELATIVE ); if (ctrl_that) ctrl_that->control.flags |= V4L2_CTRL_FLAG_GRABBED; ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_EXPOSURE_ABSOLUTE ); if (ctrl_that) ctrl_that->control.flags |= V4L2_CTRL_FLAG_GRABBED; } break; case V4L2_EXPOSURE_APERTURE_PRIORITY: { v4l2_ctrl_t *ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_EXPOSURE_ABSOLUTE ); if (ctrl_that) ctrl_that->control.flags |= V4L2_CTRL_FLAG_GRABBED; ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_IRIS_ABSOLUTE ); if (ctrl_that) ctrl_that->control.flags &= !(V4L2_CTRL_FLAG_GRABBED); ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_IRIS_RELATIVE ); if (ctrl_that) ctrl_that->control.flags &= !(V4L2_CTRL_FLAG_GRABBED); } break; case V4L2_EXPOSURE_SHUTTER_PRIORITY: { v4l2_ctrl_t *ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_IRIS_ABSOLUTE ); if (ctrl_that) ctrl_that->control.flags |= V4L2_CTRL_FLAG_GRABBED; ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_IRIS_RELATIVE ); if (ctrl_that) ctrl_that->control.flags |= V4L2_CTRL_FLAG_GRABBED; ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_EXPOSURE_ABSOLUTE ); if (ctrl_that) ctrl_that->control.flags &= !(V4L2_CTRL_FLAG_GRABBED); } break; default: { v4l2_ctrl_t *ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_EXPOSURE_ABSOLUTE ); if (ctrl_that) ctrl_that->control.flags &= !(V4L2_CTRL_FLAG_GRABBED); ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_IRIS_ABSOLUTE ); if (ctrl_that) ctrl_that->control.flags &= !(V4L2_CTRL_FLAG_GRABBED); ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_IRIS_RELATIVE ); if (ctrl_that) ctrl_that->control.flags &= !(V4L2_CTRL_FLAG_GRABBED); } break; } } break; case V4L2_CID_FOCUS_AUTO: { v4l2_ctrl_t *ctrl_this = v4l2core_get_control_by_id(vd, id); if(ctrl_this == NULL) break; if(ctrl_this->value > 0) { v4l2_ctrl_t *ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_FOCUS_ABSOLUTE); if (ctrl_that) ctrl_that->control.flags |= V4L2_CTRL_FLAG_GRABBED; ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_FOCUS_RELATIVE); if (ctrl_that) ctrl_that->control.flags |= V4L2_CTRL_FLAG_GRABBED; } else { v4l2_ctrl_t *ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_FOCUS_ABSOLUTE); if (ctrl_that) ctrl_that->control.flags &= !(V4L2_CTRL_FLAG_GRABBED); ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_FOCUS_RELATIVE); if (ctrl_that) ctrl_that->control.flags &= !(V4L2_CTRL_FLAG_GRABBED); } } break; case V4L2_CID_HUE_AUTO: { v4l2_ctrl_t *ctrl_this = v4l2core_get_control_by_id(vd, id); if(ctrl_this == NULL) break; if(ctrl_this->value > 0) { v4l2_ctrl_t *ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_HUE); if (ctrl_that) ctrl_that->control.flags |= V4L2_CTRL_FLAG_GRABBED; } else { v4l2_ctrl_t *ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_HUE); if (ctrl_that) ctrl_that->control.flags &= !(V4L2_CTRL_FLAG_GRABBED); } } break; case V4L2_CID_AUTO_WHITE_BALANCE: { v4l2_ctrl_t *ctrl_this = v4l2core_get_control_by_id(vd, id); if(ctrl_this == NULL) break; if(ctrl_this->value > 0) { v4l2_ctrl_t *ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_WHITE_BALANCE_TEMPERATURE); if (ctrl_that) ctrl_that->control.flags |= V4L2_CTRL_FLAG_GRABBED; ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_BLUE_BALANCE); if (ctrl_that) ctrl_that->control.flags |= V4L2_CTRL_FLAG_GRABBED; ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_RED_BALANCE); if (ctrl_that) ctrl_that->control.flags |= V4L2_CTRL_FLAG_GRABBED; } else { v4l2_ctrl_t *ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_WHITE_BALANCE_TEMPERATURE); if (ctrl_that) ctrl_that->control.flags &= !(V4L2_CTRL_FLAG_GRABBED); ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_BLUE_BALANCE); if (ctrl_that) ctrl_that->control.flags &= !(V4L2_CTRL_FLAG_GRABBED); ctrl_that = v4l2core_get_control_by_id( vd, V4L2_CID_RED_BALANCE); if (ctrl_that) ctrl_that->control.flags &= !(V4L2_CTRL_FLAG_GRABBED); } } break; } } /* * update flags of entire control list * args: * vd - pointer to video device data * * asserts: * vd is not null * * returns: void */ static void update_ctrl_list_flags(v4l2_dev_t *vd) { /*asserts*/ assert(vd != NULL); v4l2_ctrl_t *current = vd->list_device_controls; for(; current != NULL; current = current->next) update_ctrl_flags(vd, (int)current->control.id); } /* * Disables special auto-controls with higher IDs than * their absolute/relative counterparts * this is needed before restoring controls state * * args: * vd - pointer to video device data * id - control id * * asserts: * vd is not null * * returns: void */ void disable_special_auto (v4l2_dev_t *vd, int id) { /*asserts*/ assert(vd != NULL); v4l2_ctrl_t *current = v4l2core_get_control_by_id(vd, id); if(current && ((id == V4L2_CID_FOCUS_AUTO) || (id == V4L2_CID_HUE_AUTO))) { current->value = 0; v4l2core_set_control_value_by_id(vd, id); } } /* * goes trough the control list and updates/retrieves current values * args: * vd - pointer to video device data * * asserts: * vd is not null * vd->fd is valid * * returns: void */ void get_v4l2_control_values (v4l2_dev_t *vd) { /*asserts*/ assert(vd != NULL); assert(vd->fd > 0); if(vd->list_device_controls == NULL) { printf("V4L2_CORE: (get control values) empty control list\n"); return; } int ret = 0; struct v4l2_ext_control clist[vd->num_controls]; v4l2_ctrl_t *current = vd->list_device_controls; int count = 0; int i = 0; for(; current != NULL; current = current->next) { if(current->control.flags & V4L2_CTRL_FLAG_WRITE_ONLY) continue; clist[count].id = current->control.id; clist[count].size = 0; if(current->control.type == V4L2_CTRL_TYPE_STRING) { clist[count].size = (__u32)current->control.maximum + 1; clist[count].string = (char *) calloc(clist[count].size, sizeof(char)); if(clist[count].string == NULL) { fprintf(stderr, "V4L2_CORE: FATAL memory allocation failure (get_v4l2_control_values): %s\n", strerror(errno)); exit(-1); } } count++; if((current->next == NULL) || (current->next->cclass != current->cclass)) { struct v4l2_ext_controls ctrls /*= {0}*/; ctrls.ctrl_class = (__u32)current->cclass; ctrls.count = (__u32)count; ctrls.controls = clist; ret = xioctl(vd->fd, (int)VIDIOC_G_EXT_CTRLS, &ctrls); if(ret) { fprintf(stderr, "V4L2_CORE: (VIDIOC_G_EXT_CTRLS) failed\n"); struct v4l2_control ctrl; /*get the controls one by one*/ if( current->cclass == V4L2_CTRL_CLASS_USER && current->control.type != V4L2_CTRL_TYPE_STRING && current->control.type != V4L2_CTRL_TYPE_INTEGER64) { fprintf(stderr, "V4L2_CORE: using VIDIOC_G_CTRL for user class controls\n"); for(i=0; i < count; i++) { ctrl.id = clist[i].id; ctrl.value = 0; ret = xioctl(vd->fd, (int)VIDIOC_G_CTRL, &ctrl); if(ret) continue; clist[i].value = ctrl.value; } } else { fprintf(stderr, "V4L2_CORE: using VIDIOC_G_EXT_CTRLS on single controls for class: 0x%08x\n", current->cclass); for(i=0;i < count; i++) { ctrls.count = 1; ctrls.controls = &clist[i]; ret = xioctl(vd->fd, (int)VIDIOC_G_EXT_CTRLS, &ctrls); if(ret) fprintf(stderr, "V4L2_CORE: control id: 0x%08x failed to get (error %i)\n", clist[i].id, ret); } } } //fill in the values on the control list for(i=0; i<count; i++) { v4l2_ctrl_t *ctrl = v4l2core_get_control_by_id(vd, (int)clist[i].id); if(!ctrl) { fprintf(stderr, "V4L2_CORE: couldn't get control for id: %i\n", clist[i].id); continue; } switch(ctrl->control.type) { case V4L2_CTRL_TYPE_STRING: { /* * string gets set on VIDIOC_G_EXT_CTRLS * add the maximum size to value */ unsigned len =(unsigned) strlen(clist[i].string); unsigned max_len =(unsigned) ctrl->control.maximum; strncpy(ctrl->string, clist[i].string, max_len + 1); if(len > max_len) { ctrl->string[max_len + 1] = 0; //Null terminated fprintf(stderr, "V4L2_CORE: control (0x%08x) returned string size of %u when max is %u\n", ctrl->control.id, len, max_len); } /*clean up*/ free(clist[i].string); clist[i].string = NULL; break; } case V4L2_CTRL_TYPE_INTEGER64: ctrl->value64 = clist[i].value64; break; default: ctrl->value = clist[i].value; //printf("V4L2_CORE: control %i [0x%08x] = %i\n", // i, clist[i].id, clist[i].value); break; } } count = 0; } } update_ctrl_list_flags(vd); } /* * return the control associated to id from device list * args: * vd - pointer to video device data * id - control id * * asserts: * vd is not null * * returns: pointer to v4l2_control if succeded or null otherwise */ v4l2_ctrl_t *get_control_by_id(v4l2_dev_t *vd, int id) { /*asserts*/ assert(vd != NULL); v4l2_ctrl_t *current = vd->list_device_controls; for(; current != NULL; current = current->next) { // if(current == NULL) // break; if(current->control.id == (__u32)id) return (current); } return(NULL); } /* * updates the value for control id from the device * also updates control flags * args: * vd - pointer to video device data * id - control id * * asserts: * vd is not null * vd->fd is valid * * returns: ioctl result */ int get_control_value_by_id (v4l2_dev_t *vd, int id) { /*asserts*/ assert(vd != NULL); assert(vd->fd > 0); v4l2_ctrl_t *control = v4l2core_get_control_by_id(vd, id); int ret = 0; if(!control) return (-1); if(control->control.flags & V4L2_CTRL_FLAG_WRITE_ONLY) return (-1); if( control->cclass == V4L2_CTRL_CLASS_USER && control->control.type != V4L2_CTRL_TYPE_STRING && control->control.type != V4L2_CTRL_TYPE_INTEGER64) { struct v4l2_control ctrl; ctrl.id = control->control.id; ctrl.value = 0; ret = xioctl(vd->fd, (int)VIDIOC_G_CTRL, &ctrl); if(ret) fprintf(stderr, "V4L2_CORE: control id: 0x%08x failed to get value (error %i)\n", ctrl.id, ret); else control->value = ctrl.value; } else { struct v4l2_ext_controls ctrls /*= {0}*/; struct v4l2_ext_control ctrl = {0}; ctrl.id = control->control.id; ctrl.size = 0; if(control->control.type == V4L2_CTRL_TYPE_STRING) { ctrl.size = (__u32)control->control.maximum + 1; ctrl.string = (char *) calloc(ctrl.size, sizeof(char)); if(ctrl.string == NULL) { fprintf(stderr, "V4L2_CORE: FATAL memory allocation failure (v4l2core_get_control_value_by_id): %s\n", strerror(errno)); exit(-1); } } ctrls.ctrl_class = (__u32)control->cclass; ctrls.count = 1; ctrls.controls = &ctrl; ret = xioctl(vd->fd, (int)VIDIOC_G_EXT_CTRLS, &ctrls); if(ret) printf("control id: 0x%08x failed to get value (error %i)\n", ctrl.id, ret); else { switch(control->control.type) { case V4L2_CTRL_TYPE_STRING: { strncpy(control->string, ctrl.string, ctrl.size); //clean up free(ctrl.string); ctrl.string = NULL; break; } case V4L2_CTRL_TYPE_INTEGER64: control->value64 = ctrl.value64; break; default: control->value = ctrl.value; //printf("V4L2_CORE: control %i [0x%08x] = %i\n", // i, clist[i].id, clist[i].value); break; } } } update_ctrl_flags(vd, id); return (ret); } /* * goes trough the control list and sets values in device * args: * vd - pointer to video device data * * asserts: * vd is not null * vd->fd is valid * * returns: void */ void set_v4l2_control_values (v4l2_dev_t *vd) { /*asserts*/ assert(vd != NULL); assert(vd->fd > 0); if(vd->list_device_controls == NULL) { printf("V4L2_CORE: (set control values) empty control list\n"); return; } int ret = 0; struct v4l2_ext_control clist[vd->num_controls]; v4l2_ctrl_t *current = vd->list_device_controls; int count = 0; int i = 0; if(verbosity > 0) printf("V4L2_CORE: setting control values\n"); for(; current != NULL; current = current->next) { if(current->control.flags & V4L2_CTRL_FLAG_READ_ONLY) continue; clist[count].id = current->control.id; switch (current->control.type) { case V4L2_CTRL_TYPE_STRING: { unsigned len = (unsigned)strlen(current->string); unsigned max_len = (unsigned)current->control.maximum; if(len > max_len) { clist[count].size = max_len + 1; clist[count].string = (char *) calloc(max_len + 1, sizeof(char)); if(clist[count].string == NULL) { fprintf(stderr, "V4L2_CORE: FATAL memory allocation failure (set_v4l2_control_values): %s\n", strerror(errno)); exit(-1); } clist[count].string = strncpy(clist[count].string, current->string, max_len); clist[count].string[max_len + 1] = 0; /*NULL terminated*/ fprintf(stderr, "V4L2_CORE: control (0x%08x) trying to set string size of %u when max is %u (clip)\n", current->control.id, len, max_len); } else { clist[count].size = len + 1; clist[count].string = (char *) strdup(current->string); } break; } case V4L2_CTRL_TYPE_INTEGER64: clist[count].value64 = current->value64; break; default: if(verbosity > 0) printf("\tcontrol[%i] = %i\n", count, current->value); clist[count].value = current->value; break; } count++; if((current->next == NULL) || (current->next->cclass != current->cclass)) { struct v4l2_ext_controls ctrls /*= {0}*/; ctrls.ctrl_class = (__u32)current->cclass; ctrls.count = (__u32)count; ctrls.controls = clist; ret = xioctl(vd->fd, (int)VIDIOC_S_EXT_CTRLS, &ctrls); if(ret) { fprintf(stderr, "V4L2_CORE: VIDIOC_S_EXT_CTRLS for multiple controls failed (error %i)\n", ret); struct v4l2_control ctrl; /*set the controls one by one*/ if( current->cclass == V4L2_CTRL_CLASS_USER && current->control.type != V4L2_CTRL_TYPE_STRING && current->control.type != V4L2_CTRL_TYPE_INTEGER64) { fprintf(stderr, "V4L2_CORE: using VIDIOC_S_CTRL for user class controls\n"); for(i=0;i < count; i++) { ctrl.id = clist[i].id; ctrl.value = clist[i].value; ret = xioctl(vd->fd, (int)VIDIOC_S_CTRL, &ctrl); if(ret) { v4l2_ctrl_t *ctrl = v4l2core_get_control_by_id(vd, (int)clist[i].id); if(ctrl) fprintf(stderr, "V4L2_CORE: control(0x%08x) \"%s\" failed to set (error %i)\n", clist[i].id, ctrl->control.name, ret); else fprintf(stderr, "V4L2_CORE: control(0x%08x) failed to set (error %i)\n", clist[i].id, ret); } } } else { fprintf(stderr, "V4L2_CORE: using VIDIOC_S_EXT_CTRLS on single controls for class: 0x%08x\n", current->cclass); for(i=0;i < count; i++) { ctrls.count = 1; ctrls.controls = &clist[i]; ret = xioctl(vd->fd, (int)VIDIOC_S_EXT_CTRLS, &ctrls); v4l2_ctrl_t *ctrl = v4l2core_get_control_by_id(vd, (int)clist[i].id); if(ret) { if(ctrl) fprintf(stderr, "V4L2_CORE: control(0x%08x) \"%s\" failed to set (error %i)\n", clist[i].id, ctrl->control.name, ret); else fprintf(stderr, "V4L2_CORE: control(0x%08x) failed to set (error %i)\n", clist[i].id, ret); } if(ctrl && ctrl->control.type == V4L2_CTRL_TYPE_STRING) { free(clist[i].string); //free allocated string clist[i].string = NULL; } } } } count = 0; } } } /* * goes trough the control list and sets values in device to default * args: * vd - pointer to video device data * * asserts: * vd is not null * * returns: void */ void set_control_defaults(v4l2_dev_t *vd) { /*asserts*/ assert(vd != NULL); if(vd->list_device_controls == NULL) { printf("V4L2_CORE: (set control defaults) empty control list\n"); return; } v4l2_ctrl_t *current = vd->list_device_controls; //v4l2_ctrl_t *next = current->next; if(verbosity > 0) printf("V4L2_CORE: loading defaults\n"); int i = 0; for(; current != NULL; current = current->next, ++i) { if(current->control.flags & V4L2_CTRL_FLAG_READ_ONLY) continue; switch (current->control.type) { case V4L2_CTRL_TYPE_STRING: /* do string controls have a default value?*/ break; case V4L2_CTRL_TYPE_INTEGER64: /* do int64 controls have a default value?*/ break; default: /*if its one of the special auto controls disable it first*/ disable_special_auto (vd, (int)current->control.id); if(verbosity > 1) printf("\tdefault[%i] = %i\n", i, current->control.default_value); current->value = current->control.default_value; break; } } set_v4l2_control_values(vd); get_v4l2_control_values(vd); } /* * sets the value of control id in device * args: * vd - pointer to video device data * id - control id * * asserts: * vd is not null * vd->fd is valid * * returns: ioctl result */ int set_control_value_by_id(v4l2_dev_t *vd, int id) { /*asserts*/ assert(vd != NULL); assert(vd->fd > 0); v4l2_ctrl_t *control = v4l2core_get_control_by_id(vd, id); int ret = 0; if(!control) return (-1); if(control->control.flags & V4L2_CTRL_FLAG_READ_ONLY) return (-1); if((id == V4L2_CID_PAN_RELATIVE || id == V4L2_CID_TILT_RELATIVE) && vd->pantilt_unit_id > 0) { /*use raw control in this case - prevents uvcvideo cache bug*/ uint32_t pantilt = 0; if(id == V4L2_CID_PAN_RELATIVE) pantilt |= (uint32_t) control->value; else pantilt |= ((uint32_t) control->value) << 16; return query_xu_control(vd, vd->pantilt_unit_id, 1, UVC_SET_CUR, &pantilt); } if( control->cclass == V4L2_CTRL_CLASS_USER && control->control.type != V4L2_CTRL_TYPE_STRING && control->control.type != V4L2_CTRL_TYPE_INTEGER64) { //using VIDIOC_G_CTRL for user class controls struct v4l2_control ctrl; ctrl.id = control->control.id; ctrl.value = control->value; ret = xioctl(vd->fd, (int)VIDIOC_S_CTRL, &ctrl); } else { //using VIDIOC_G_EXT_CTRLS on single controls struct v4l2_ext_controls ctrls /*= {0}*/; struct v4l2_ext_control ctrl = {0}; ctrl.id = control->control.id; switch (control->control.type) { case V4L2_CTRL_TYPE_STRING: { unsigned len = (unsigned)strlen(control->string); unsigned max_len = (unsigned)control->control.maximum; if(len > max_len) { ctrl.size = max_len + 1; ctrl.string = (char *) calloc(max_len + 1, sizeof(char)); if(ctrl.string == NULL) { fprintf(stderr, "V4L2_CORE: FATAL memory allocation failure (v4l2core_set_control_value_by_id): %s\n", strerror(errno)); exit(-1); } ctrl.string = strncpy(ctrl.string, control->string, max_len); ctrl.string[max_len + 1] = 0; /*NULL terminated*/ fprintf(stderr, "V4L2_CORE: control (0x%08x) trying to set string size of %u when max is %u (clip)\n", control->control.id, len, max_len); } else { ctrl.size = len + 1; ctrl.string = (char *) strdup(control->string); } break; } case V4L2_CTRL_TYPE_INTEGER64: ctrl.value64 = control->value64; break; default: ctrl.value = control->value; break; } ctrls.ctrl_class = (__u32)control->cclass; ctrls.count = 1; ctrls.controls = &ctrl; ret = xioctl(vd->fd, (int)VIDIOC_S_EXT_CTRLS, &ctrls); if(ret) printf("control id: 0x%08x failed to set (error %i)\n", ctrl.id, ret); if(control->control.type == V4L2_CTRL_TYPE_STRING) { free(ctrl.string); //clean up string allocation ctrl.string = NULL; } } //update real value get_control_value_by_id(vd, id); return (ret); } /* * free control list * args: * vd - pointer to video device data * * asserts: * vd is not null * * returns: void */ void free_v4l2_control_list(v4l2_dev_t *vd) { /*asserts*/ assert(vd != NULL); if(vd->list_device_controls == NULL) { return; } v4l2_ctrl_t *first = vd->list_device_controls; while (first != NULL) { v4l2_ctrl_t *next = first->next; if(first->string) free(first->string); if(first->menu) free(first->menu); if(first->menu_entry) { int i = 0; for(i = 0; i < first->menu_entries; i++) free(first->menu_entry[i]); free(first->menu_entry); } free(first); first = next; } vd->list_device_controls = NULL; //unsubscibe control events v4l2_unsubscribe_control_events(vd); }
46,871
C
.c
1,331
26.604057
132
0.546334
linuxdeepin/dtkmultimedia
3
16
2
LGPL-3.0
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
15,285,544
control_profile.c
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam_v4l2core/control_profile.c
/*******************************************************************************# # guvcview http://guvcview.sourceforge.net # # # # Paulo Assis <[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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # ********************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <linux/videodev2.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <errno.h> #include <assert.h> #include "gviewv4l2core.h" #include "v4l2_controls.h" #include "control_profile.h" #include "cameraconfig.h" #define PACKAGE_STRING "cheese 1.0" extern int verbosity; /* * save the device control values into a profile file * args: * vd - pointer to video device data * filename - profile filename * * asserts: * vd is not null * * returns: error code (0 -E_OK) */ int save_control_profile(v4l2_dev_t *vd, const char *filename) { /*assertions*/ assert(vd != NULL); FILE *fp; fp = fopen(filename, "w"); if( fp == NULL ) { fprintf(stderr, "V4L2_CORE: (save_control_profile) Could not open %s for write: %s\n", filename, strerror(errno)); return (E_FILE_IO_ERR); } else { if (vd->list_device_controls) { v4l2_ctrl_t *current = vd->list_device_controls; /*write header*/ fprintf(fp, "#V4L2/CTRL/0.0.2\n"); fprintf(fp, "APP{\"%s\"}\n", PACKAGE_STRING); /*write control data*/ fprintf(fp, "# control data\n"); for( ; current != NULL; current = current->next) { if((current->control.flags & V4L2_CTRL_FLAG_WRITE_ONLY) || (current->control.flags & V4L2_CTRL_FLAG_READ_ONLY) || (current->control.flags & V4L2_CTRL_FLAG_GRABBED)) { if(verbosity > 0) printf("V4L2_CORE: (save_control_profile) skiping control 0x%08x\n", current->control.id); continue; } fprintf(fp, "#%s\n", current->control.name); switch(current->control.type) { case V4L2_CTRL_TYPE_STRING : fprintf(fp, "ID{0x%08x};CHK{%i:%i:%i:0}=STR{\"%s\"}\n", current->control.id, current->control.minimum, current->control.maximum, current->control.step, current->string); break; case V4L2_CTRL_TYPE_INTEGER64 : fprintf(fp, "ID{0x%08x};CHK{0:0:0:0}=VAL64{%" PRId64 "}\n", current->control.id, current->value64); break; default : fprintf(fp, "ID{0x%08x};CHK{%i:%i:%i:%i}=VAL{%i}\n", current->control.id, current->control.minimum, current->control.maximum, current->control.step, current->control.default_value, current->value); break; } } } } fflush(fp); /*flush stream buffers to filesystem*/ if(fsync(fileno(fp)) || fclose(fp)) { fprintf(stderr, "V4L2_CORE: (save_control_profile) write to file failed: %s\n", strerror(errno)); return(E_FILE_IO_ERR); } return (E_OK); } /* * load the device control values from a profile file * args: * vd - pointer to video device data * filename - profile filename * * asserts: * vd is not null * * returns: error code (0 -E_OK) */ int load_control_profile(v4l2_dev_t *vd, const char *filename) { /*assertions*/ assert(vd != NULL); FILE *fp; int major=0, minor=0, rev=0; if((fp = fopen(filename,"r"))!=NULL) { char line[200]; if(fgets(line, sizeof(line), fp) != NULL) { if(sscanf(line,"#V4L2/CTRL/%3i.%3i.%3i", &major, &minor, &rev) == 3) { //check standard version if needed } else { fprintf(stderr, "V4L2_CORE: (load_control_profile) no valid header found\n"); fclose(fp); return(E_NO_DATA); } } else { fprintf(stderr, "V4L2_CORE: (load_control_profile) no valid header found\n"); fclose(fp); return(E_NO_DATA); } while (fgets(line, sizeof(line), fp) != NULL) { int id = 0; int min = 0, max = 0, step = 0, def = 0; int32_t val = 0; int64_t val64 = 0; if ((line[0]!='#') && (line[0]!='\n')) { if(sscanf(line,"ID{0x%08i};CHK{%5i:%5i:%5i:%5i}=VAL{%5i}", &id, &min, &max, &step, &def, &val) == 6) { v4l2_ctrl_t *current = v4l2core_get_control_by_id(vd, id); if(current) { /*check values*/ if(current->control.minimum == min && current->control.maximum == max && current->control.step == step && current->control.default_value == def) { current->value = val; } } } else if(sscanf(line,"ID{0x%08x};CHK{0:0:0:0}=VAL64{%" PRId64 "}", &id, &val64) == 2) { v4l2_ctrl_t *current = v4l2core_get_control_by_id(vd, id); if(current) { current->value64 = val64; } } else if(sscanf(line,"ID{0x%08i};CHK{%5i:%5i:%5i:0}=STR{\"%*s\"}", &id, &min, &max, &step) == 5) { v4l2_ctrl_t *current = v4l2core_get_control_by_id(vd, id); if(current) { /*check values*/ if(current->control.minimum == min && current->control.maximum == max && current->control.step == step) { char str[max+1]; char fmt[48]; sprintf(fmt,"ID{0x%%*x};CHK{%%*i:%%*i:%%*i:0}==STR{\"%%%is\"}", max); sscanf(line, fmt, str); /*we are only scannig for max chars so this should never happen*/ if(strlen(str) > (size_t)max) /*FIXME: should also check (minimum +N*step)*/ { fprintf(stderr, "V4L2_CORE: (load_control_profile) string bigger than maximum buffer size (%i > %i)\n", (int) strlen(str), max); if(current->string) free(current->string); current->string = strndup(str, (size_t)max); /*FIXME: does max includes '\0' ?*/ } else { if(current->string) free(current->string); current->string = strndup(str, strlen(str)+1); } } } } } } set_v4l2_control_values(vd); get_v4l2_control_values(vd); } else { fprintf(stderr, "V4L2_CORE: (load_control_profile) Could not open for %s read: %s\n", filename, strerror(errno)); return (E_FILE_IO_ERR); } fclose(fp); return (E_OK); }
7,657
C
.c
234
27.367521
135
0.528514
linuxdeepin/dtkmultimedia
3
16
2
LGPL-3.0
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
15,285,548
v4l2_core.h
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam_v4l2core/v4l2_core.h
/*******************************************************************************# # guvcview http://guvcview.sourceforge.net # # # # Paulo Assis <[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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # ********************************************************************************/ #ifndef V4L2CORE_H #define V4L2CORE_H #include "gviewv4l2core.h" #include "gview.h" /* * video device data */ struct _v4l2_dev_t { int fd; // device file descriptor char *videodevice; // video device string (default "/dev/video0)" __MUTEX_TYPE mutex; // device mutex int cap_meth; // capture method: IO_READ or IO_MMAP v4l2_stream_formats_t* list_stream_formats; //list of available stream formats int numb_formats; //list size //int current_format_index; //index of current stream format //int current_resolution_index; //index of current resolution for current format struct v4l2_capability cap; // v4l2 capability struct struct v4l2_format format; // v4l2 format struct struct v4l2_buffer buf; // v4l2 buffer struct struct v4l2_requestbuffers rb; // v4l2 request buffers struct struct v4l2_streamparm streamparm; // v4l2 stream parameters struct struct v4l2_event_subscription evsub;// v4l2 event subscription struct int requested_fmt; //requested format (may differ from format.fmt.pix.pixelformat) int fps_num; //fps numerator int fps_denom; //fps denominator double real_fps; //real fps (calculated from number of captured frames) uint8_t streaming; // flag device stream : STRM_STOP ; STRM_REQ_STOP; STRM_OK uint64_t frame_index; // captured frame index from 0 to max(uint64_t) void *mem[NB_BUFFER]; // memory buffers for mmap driver frames uint32_t buff_length[NB_BUFFER]; // memory buffers length as set by VIDIOC_QUERYBUF uint32_t buff_offset[NB_BUFFER]; // memory buffers offset as set by VIDIOC_QUERYBUF v4l2_frame_buff_t *frame_queue; //frame queue int frame_queue_size; //size of frame queue (in frames) uint8_t h264_unit_id; // uvc h264 unit id, if <= 0 then uvc h264 is not supported uint8_t h264_no_probe_default; // flag core to use the preset h264_config_probe_req data (don't reset to default before commit) uvcx_video_config_probe_commit_t h264_config_probe_req; //probe commit struct for h264 streams uint8_t *h264_last_IDR; // last IDR frame retrieved from uvc h264 stream int h264_last_IDR_size; // last IDR frame size uint8_t *h264_SPS; // h264 SPS info uint16_t h264_SPS_size; // SPS size uint8_t *h264_PPS; // h264 PPS info uint16_t h264_PPS_size; // PPS size int this_device; // index of this device in device list v4l2_ctrl_t* list_device_controls; //null terminated linked list of available device controls int num_controls; //number of controls in list uint8_t isbayer; //flag if we are streaming bayer data in yuyv frame (logitech only) uint8_t bayer_pix_order; //bayer pixel order int pan_step; //pan step for relative pan tilt controls (logitech sphere/orbit/BCC950) int tilt_step; //tilt step for relative pan tilt controls (logitech sphere/orbit/BCC950) int has_focus_control_id; //it's set to control id if a focus control is available (enables software autofocus) int has_pantilt_control_id; //it's set to 1 if a pan/tilt control is available uint8_t pantilt_unit_id; //logitech peripheral V3 unit id (if any) }; void /*__attribute__ ((constructor))*/ v4l2core_init(); #endif
5,279
C
.c
76
67.328947
133
0.554977
linuxdeepin/dtkmultimedia
3
16
2
LGPL-3.0
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
15,285,557
colorspaces.c
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam_v4l2core/colorspaces.c
/*******************************************************************************# # guvcview http://guvcview.sourceforge.net # # # # Paulo Assis <[email protected]> # # Nobuhiro Iwamatsu <[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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # ********************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <assert.h> #include "gview.h" #include "cameraconfig.h" extern int verbosity; /*------------------------------- Color space conversions --------------------*/ /*---------------- raw bayer -------------*/ /* raw bayer functions * from libv4l bayer.c, (C) 2008 Hans de Goede <[email protected]> * Note: original bayer_to_bgr24 code from : * 1394-Based Digital Camera Control Library * * Bayer pattern decoding functions * Written by Damien Douxchamps and Frederic Devernay * */ static void convert_border_bayer_line_to_bgr24( uint8_t* bayer, uint8_t* adjacent_bayer, uint8_t *bgr, int width, uint8_t start_with_green, uint8_t blue_line) { //LMH0612之前是强制类型转换int到uint8_t,这里初始化就为uint8_t uint8_t t0, t1; if (start_with_green) { /* First pixel */ if (blue_line) { *bgr++ = bayer[1]; *bgr++ = bayer[0]; *bgr++ = adjacent_bayer[0]; } else { *bgr++ = adjacent_bayer[0]; *bgr++ = bayer[0]; *bgr++ = bayer[1]; } /* Second pixel */ t0 = (bayer[0] + bayer[2] + adjacent_bayer[1] + 1) / 3; t1 = (adjacent_bayer[0] + adjacent_bayer[2] + 1) >> 1; if (blue_line) { *bgr++ = bayer[1]; *bgr++ = t0; *bgr++ = t1; } else { *bgr++ = t1; *bgr++ = t0; *bgr++ = bayer[1]; } bayer++; adjacent_bayer++; width -= 2; } else { /* First pixel */ t0 = (bayer[1] + adjacent_bayer[0] + 1) >> 1; if (blue_line) { *bgr++ = bayer[0]; *bgr++ = t0; *bgr++ = adjacent_bayer[1]; } else { *bgr++ = adjacent_bayer[1]; *bgr++ = t0; *bgr++ = bayer[0]; } width--; } if (blue_line) { for ( ; width > 2; width -= 2) { t0 = (bayer[0] + bayer[2] + 1) >> 1; *bgr++ = t0; *bgr++ = bayer[1]; *bgr++ = adjacent_bayer[1]; bayer++; adjacent_bayer++; t0 = (bayer[0] + bayer[2] + adjacent_bayer[1] + 1) / 3; t1 = (adjacent_bayer[0] + adjacent_bayer[2] + 1) >> 1; *bgr++ = bayer[1]; *bgr++ = t0; *bgr++ = t1; bayer++; adjacent_bayer++; } } else { for ( ; width > 2; width -= 2) { t0 = (bayer[0] + bayer[2] + 1) >> 1; *bgr++ = adjacent_bayer[1]; *bgr++ = bayer[1]; *bgr++ = t0; bayer++; adjacent_bayer++; t0 = (bayer[0] + bayer[2] + adjacent_bayer[1] + 1) / 3; t1 = (adjacent_bayer[0] + adjacent_bayer[2] + 1) >> 1; *bgr++ = t1; *bgr++ = t0; *bgr++ = bayer[1]; bayer++; adjacent_bayer++; } } if (width == 2) { /* Second to last pixel */ t0 = (bayer[0] + bayer[2] + 1) >> 1; if (blue_line) { *bgr++ = t0; *bgr++ = bayer[1]; *bgr++ = adjacent_bayer[1]; } else { *bgr++ = adjacent_bayer[1]; *bgr++ = bayer[1]; *bgr++ = t0; } /* Last pixel */ t0 = (bayer[1] + adjacent_bayer[2] + 1) >> 1; if (blue_line) { *bgr++ = bayer[2]; *bgr++ = t0; *bgr++ = adjacent_bayer[1]; } else { *bgr++ = adjacent_bayer[1]; *bgr++ = t0; *bgr++ = bayer[2]; } } else { /* Last pixel */ if (blue_line) { *bgr++ = bayer[0]; *bgr++ = bayer[1]; *bgr++ = adjacent_bayer[1]; } else { *bgr++ = adjacent_bayer[1]; *bgr++ = bayer[1]; *bgr++ = bayer[0]; } } } /* * From libdc1394, which on turn was based on OpenCV's Bayer decoding */ static void bayer_to_rgbbgr24(uint8_t *bayer, uint8_t *bgr, int width, int height, uint8_t start_with_green, uint8_t blue_line) { /* render the first line */ convert_border_bayer_line_to_bgr24(bayer, bayer + width, bgr, width, start_with_green, blue_line); bgr += width * 3; /* reduce height by 2 because of the special case top/bottom line */ for (height -= 2; height; height--) { //LMH0612之前是强制类型转换int到uint8_t,这里初始化就为uint8_t uint8_t t0, t1; /* (width - 2) because of the border */ uint8_t *bayerEnd = bayer + (width - 2); if (start_with_green) { /* OpenCV has a bug in the next line, which was t0 = (bayer[0] + bayer[width * 2] + 1) >> 1; */ t0 = (bayer[1] + bayer[width * 2 + 1] + 1) >> 1; /* Write first pixel */ t1 = (bayer[0] + bayer[width * 2] + bayer[width + 1] + 1) / 3; if (blue_line) { *bgr++ = t0; *bgr++ = t1; *bgr++ = bayer[width]; } else { *bgr++ = bayer[width]; *bgr++ = t1; *bgr++ = t0; } /* Write second pixel */ t1 = (bayer[width] + bayer[width + 2] + 1) >> 1; if (blue_line) { *bgr++ = t0; *bgr++ = bayer[width + 1]; *bgr++ = t1; } else { *bgr++ = t1; *bgr++ = bayer[width + 1]; *bgr++ = t0; } bayer++; } else { /* Write first pixel */ t0 = (bayer[0] + bayer[width * 2] + 1) >> 1; if (blue_line) { *bgr++ = t0; *bgr++ = bayer[width]; *bgr++ = bayer[width + 1]; } else { *bgr++ = bayer[width + 1]; *bgr++ = bayer[width]; *bgr++ = t0; } } if (blue_line) { for (; bayer <= bayerEnd - 2; bayer += 2) { t0 = (bayer[0] + bayer[2] + bayer[width * 2] + bayer[width * 2 + 2] + 2) >> 2; t1 = (bayer[1] + bayer[width] + bayer[width + 2] + bayer[width * 2 + 1] + 2) >> 2; *bgr++ = t0; *bgr++ = t1; *bgr++ = bayer[width + 1]; t0 = (bayer[2] + bayer[width * 2 + 2] + 1) >> 1; t1 = (bayer[width + 1] + bayer[width + 3] + 1) >> 1; *bgr++ = t0; *bgr++ = bayer[width + 2]; *bgr++ = t1; } } else { for (; bayer <= bayerEnd - 2; bayer += 2) { t0 = (bayer[0] + bayer[2] + bayer[width * 2] + bayer[width * 2 + 2] + 2) >> 2; t1 = (bayer[1] + bayer[width] + bayer[width + 2] + bayer[width * 2 + 1] + 2) >> 2; *bgr++ = bayer[width + 1]; *bgr++ = t1; *bgr++ = t0; t0 = (bayer[2] + bayer[width * 2 + 2] + 1) >> 1; t1 = (bayer[width + 1] + bayer[width + 3] + 1) >> 1; *bgr++ = t1; *bgr++ = bayer[width + 2]; *bgr++ = t0; } } if (bayer < bayerEnd) { /* write second to last pixel */ t0 = (bayer[0] + bayer[2] + bayer[width * 2] + bayer[width * 2 + 2] + 2) >> 2; t1 = (bayer[1] + bayer[width] + bayer[width + 2] + bayer[width * 2 + 1] + 2) >> 2; if (blue_line) { *bgr++ = t0; *bgr++ = t1; *bgr++ = bayer[width + 1]; } else { *bgr++ = bayer[width + 1]; *bgr++ = t1; *bgr++ = t0; } /* write last pixel */ t0 = (bayer[2] + bayer[width * 2 + 2] + 1) >> 1; if (blue_line) { *bgr++ = t0; *bgr++ = bayer[width + 2]; *bgr++ = bayer[width + 1]; } else { *bgr++ = bayer[width + 1]; *bgr++ = bayer[width + 2]; *bgr++ = t0; } bayer++; } else { /* write last pixel */ t0 = (bayer[0] + bayer[width * 2] + 1) >> 1; t1 = (bayer[1] + bayer[width * 2 + 1] + bayer[width] + 1) / 3; if (blue_line) { *bgr++ = t0; *bgr++ = t1; *bgr++ = bayer[width + 1]; } else { *bgr++ = bayer[width + 1]; *bgr++ = t1; *bgr++ = t0; } } /* skip 2 border pixels */ bayer += 2; blue_line = !blue_line; start_with_green = !start_with_green; } /* render the last line */ convert_border_bayer_line_to_bgr24(bayer + width, bayer, bgr, width, !start_with_green, !blue_line); } /* * convert bayer raw data to rgb24 * args: * pBay: pointer to buffer containing Raw bayer data * pRGB24: pointer to buffer containing rgb24 data * width: picture width * height: picture height * pix_order: bayer pixel order (0=gb/rg 1=gr/bg 2=bg/gr 3=rg/bg) * * asserts: * none * * returns: none */ void bayer_to_rgb24(uint8_t *pBay, uint8_t *pRGB24, int width, int height, int pix_order) { switch (pix_order) { //conversion functions are build for bgr, by switching b and r lines we get rgb case 0: /* gbgbgb... | rgrgrg... (V4L2_PIX_FMT_SGBRG8)*/ bayer_to_rgbbgr24(pBay, pRGB24, width, height, TRUE, FALSE); break; case 1: /* grgrgr... | bgbgbg... (V4L2_PIX_FMT_SGRBG8)*/ bayer_to_rgbbgr24(pBay, pRGB24, width, height, TRUE, TRUE); break; case 2: /* bgbgbg... | grgrgr... (V4L2_PIX_FMT_SBGGR8)*/ bayer_to_rgbbgr24(pBay, pRGB24, width, height, FALSE, FALSE); break; case 3: /* rgrgrg... ! gbgbgb... (V4L2_PIX_FMT_SRGGB8)*/ bayer_to_rgbbgr24(pBay, pRGB24, width, height, FALSE, TRUE); break; default: /* default is 0*/ bayer_to_rgbbgr24(pBay, pRGB24, width, height, TRUE, FALSE); break; } } /*------------------ YU12 ----------------------*/ /* *convert from packed 422 yuv (yuyv) to 420 planar (yu12) * args: * out - pointer to output yu12 planar data buffer * in - pointer to input yuyv packed data buffer * width - frame width * height - frame height * * asserts: * in is not null * out is not null * * returns: none */ void yuyv_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); int w = 0, h = 0; uint8_t *in1 = in; //first line uint8_t *in2 = in1 + (width * 2); //second line in yuyv buffer uint8_t *py1 = out; // first line uint8_t *py2 = py1 + width; //second line uint8_t *pu = py1 + (width * height); uint8_t *pv = pu + ((width * height) / 4); for(h = 0; h < height; h+=2) { in2 = in1 + (width * 2); py2 = py1 + width; for(w = 0; w < width; w+=2) //yuyv 2 bytes per sample { //printf("decoding: h:%i w:%i\n", h, w); *py1++ = *in1++; *py2++ = *in2++; *pu++ = ((*in1++) + (*in2++)) /2; //average u samples *py1++ = *in1++; *py2++ = *in2++; *pv++ = ((*in1++) + (*in2++)) /2; //average v samples } in1 = in2; py1 = py2; } } /* *convert from packed 422 yuv (yvyu) to 420 planar (yu12) * args: * out - pointer to output yu12 planar data buffer * in - pointer to input yvyu packed data buffer * width - frame width * height - frame height * * asserts: * in is not null * out is not null * * returns: none */ void yvyu_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); int w = 0, h = 0; uint8_t *in1 = in; //first line uint8_t *in2 = in1 + (width * 2); //second line in yvyu buffer uint8_t *py1 = out; // first line uint8_t *py2 = py1 + width; //second line uint8_t *pu = py1 + (width * height); uint8_t *pv = pu + ((width * height) / 4); for(h = 0; h < height; h+=2) { in2 = in1 + (width * 2); py2 = py1 + width; for(w = 0; w < width; w+=2) //yuyv 2 bytes per sample { //printf("decoding: h:%i w:%i\n", h, w); *py1++ = *in1++; *py2++ = *in2++; *pv++ = ((*in1++) + (*in2++)) /2; //average v samples *py1++ = *in1++; *py2++ = *in2++; *pu++ = ((*in1++) + (*in2++)) /2; //average u samples } in1 = in2; py1 = py2; } } /* *convert from packed 422 yuv (uyvy) to 420 planar (yu12) * args: * out - pointer to output yu12 planar data buffer * in - pointer to input uyvy packed data buffer * width - frame width * height - frame height * * asserts: * in is not null * out is not null * * returns: none */ void uyvy_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); int w = 0, h = 0; uint8_t *in1 = in; //first line uint8_t *in2 = in1 + (width * 2); //second line in yuyv buffer uint8_t *py1 = out; // first line uint8_t *py2 = py1 + width; //second line uint8_t *pu = py1 + (width * height); uint8_t *pv = pu + ((width * height) / 4); for(h = 0; h < height; h+=2) { in2 = in1 + (width * 2); py2 = py1 + width; for(w = 0; w < width; w+=2) //yuyv 2 bytes per sample { *pu++ = ((*in1++) + (*in2++)) /2; //average u samples *py1++ = *in1++; *py2++ = *in2++; *pv++ = ((*in1++) + (*in2++)) /2; //average v samples *py1++ = *in1++; *py2++ = *in2++; } in1 = in2; py1 = py2; } } /* *convert from packed 422 yuv (vyuy) to 420 planar (yu12) * args: * out - pointer to output yu12 planar data buffer * in - pointer to input vyuy packed data buffer * width - frame width * height - frame height * * asserts: * in is not null * out is not null * * returns: none */ void vyuy_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); int w = 0, h = 0; int y_sizeline = width; //LMH0612消除警告,该地方c_sizeline并未使用到 //int c_sizeline = width/2; uint8_t *in1 = in; //first line uint8_t *in2 = in1 + (width * 2); //second line in yuyv buffer uint8_t *py1 = out; // first line uint8_t *py2 = py1 + y_sizeline; //second line uint8_t *pu = py1 + (width * height); uint8_t *pv = pu + ((width * height) / 4); for(h = 0; h < height; h+=2) { in2 = in1 + (width * 2); py2 = py1 + width; for(w = 0; w < width; w+=2) //yuyv 2 bytes per sample { *pv++ = ((*in1++) + (*in2++)) /2; //average v samples *py1++ = *in1++; *py2++ = *in2++; *pu++ = ((*in1++) + (*in2++)) /2; //average u samples *py1++ = *in1++; *py2++ = *in2++; } in1 = in2; py1 = py2; } } /* *convert from 422 planar yuv to 420 planar (yu12) * args: * out - pointer to output yu12 planar data buffer * in - pointer to input 422 planar data buffer * width - frame width * height - frame height * * asserts: * in is not null * out is not null * * returns: none */ void yuv422p_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); /*copy y data*/ //LMH0612,强制类型转换警告消除 memcpy(out, in, (unsigned long)width*(unsigned long)height); int w = 0, h = 0; //LMH0612后面并未使用到c_sizeline //int c_sizeline = width/2; uint8_t *pu = out + (width * height); uint8_t *inu1 = in + (width * height); uint8_t *inu2 = inu1 + (width/2); uint8_t *pv = pu + ((width * height) / 4); uint8_t *inv1 = inu1 + ((width * height) / 2); uint8_t *inv2 = inv1 + (width / 2); for(h = 0; h < height; h+=2) { inu2 = inu1 + (width / 2); inv2 = inv1 + (width / 2); for(w = 0; w < width/2; w++) { *pu++ = ((*inu1++) + (*inu2++)) /2; //average u sample *pv++ = ((*inv1++) + (*inv2++)) /2; //average v samples } inu1 = inu2; inv1 = inv2; } } /* * convert yyuv (packed) to yuv420 planar (yu12) * args: * out: pointer to output buffer (yu12) * in: pointer to input buffer containing yyuv packed data frame * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void yyuv_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); int w = 0, h = 0; int y_sizeline = width; //LMH0612后面并未使用c_sizeline // int c_sizeline = width/2; uint8_t *in1 = in; //first line uint8_t *in2 = in1 + (width * 2); //second line in yyuv buffer uint8_t *py1 = out; // first line uint8_t *py2 = py1 + y_sizeline; //second line uint8_t *pu = py1 + (width * height); uint8_t *pv = pu + ((width * height) / 4); for(h = 0; h < height; h+=2) { in2 = in1 + (width * 2); py2 = py1 + width; for(w = 0; w < width; w+=2) //yyuv 2 bytes per sample { *py1++ = *in1++; *py1++ = *in1++; *py2++ = *in2++; *py2++ = *in2++; *pu++ = ((*in1++) + (*in2++)) /2; //average v samples *pv++ = ((*in1++) + (*in2++)) /2; //average u samples } in1 = in2; py1 = py2; } } /* * convert y444 (packed) to yuv420 planar (yu12) * args: * out: pointer to output buffer (yu12) * in: pointer to input buffer containing y444 (yuv-4-4-4) packed data frame * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void y444_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); int w = 0, h = 0; uint8_t *in1 = in; //first line uint8_t *in2 = in1 + (width * 2); //second line uint8_t *py1 = out; // first line uint8_t *py2 = py1 + width; //second line uint8_t *pu = py1 + (width * height); uint8_t *pv = pu + ((width * height) / 4); for(h = 0; h < height; h+=2) { in2 = in1 + (width * 2); py2 = py1 + width; for(w = 0; w < (width*2); w+=4) { uint8_t yuv10 = *in1++; uint8_t yuv11 = *in1++; uint8_t yuv12 = *in1++; uint8_t yuv13 = *in1++; uint8_t yuv20 = *in2++; uint8_t yuv21 = *in2++; uint8_t yuv22 = *in2++; uint8_t yuv23 = *in2++; *py1++ = (uint8_t) (yuv11 << 4) & 0xF0; *py1++ = (uint8_t) (yuv13 << 4) & 0xF0; *py2++ = (uint8_t) (yuv21 << 4) & 0xF0; *py2++ = (uint8_t) (yuv23 << 4) & 0xF0; uint8_t u10 = yuv10 & 0xF0; uint8_t u11 = yuv12 & 0xF0; uint8_t u1 = (u10 + u11) /2; uint8_t v10 = (yuv10 << 4) & 0xF0; uint8_t v11 = (yuv12 << 4) & 0xF0; uint8_t v1 = (v10 + v11) /2; uint8_t u20 = yuv20 & 0xF0; uint8_t u21 = yuv22 & 0xF0; uint8_t u2 = (u20 + u21) /2; uint8_t v20 = (yuv20 << 4) & 0xF0; uint8_t v21 = (yuv22 << 4) & 0xF0; uint8_t v2 = (v20 +v21) /2; *pu++ = (u1 + u2) /2; *pv++ = (v1 + v2) /2; } in1 = in2; py1 = py2; } } /* * convert yuvo (packed) to yuv420 planar (yu12) * args: * out: pointer to output buffer (yu12) * in: pointer to input buffer containing yuvo (yuv-5-5-5) packed data frame * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void yuvo_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); int w = 0, h = 0; uint8_t *in1 = in; //first line uint8_t *in2 = in1 + (width * 2); //second line uint8_t *py1 = out; // first line uint8_t *py2 = py1 + width; //second line uint8_t *pu = py1 + (width * height); uint8_t *pv = pu + ((width * height) / 4); for(h = 0; h < height; h+=2) { in2 = in1 + (width * 2); py2 = py1 + width; for(w = 0; w < (width*2); w+=4) { uint8_t yuv10 = *in1++; uint8_t yuv11 = *in1++; uint8_t yuv12 = *in1++; uint8_t yuv13 = *in1++; uint8_t yuv20 = *in2++; uint8_t yuv21 = *in2++; uint8_t yuv22 = *in2++; uint8_t yuv23 = *in2++; *py1++ = (uint8_t) (yuv11 << 1) & 0xF8; *py1++ = (uint8_t) (yuv13 << 1) & 0xF8; *py2++ = (uint8_t) (yuv21 << 1) & 0xF8; *py2++ = (uint8_t) (yuv23 << 1) & 0xF8; uint8_t u10 = ((yuv10 >> 2) & 0x38) | ((yuv11 << 6) & 0xC0); uint8_t u11 = ((yuv12 >> 2) & 0x38) | ((yuv13 << 6) & 0xC0); uint8_t u1 = (u10 + u11) /2; uint8_t v10 = (yuv10 << 3) & 0xF8; uint8_t v11 = (yuv12 << 3) & 0xF8; uint8_t v1 = (v10 + v11) /2; uint8_t u20 = ((yuv20 >> 2) & 0x38) | ((yuv21 << 6) & 0xC0); uint8_t u21 = ((yuv22 >> 2) & 0x38) | ((yuv23 << 6) & 0xC0); uint8_t u2 = (u20 + u21) /2; uint8_t v20 = (yuv20 << 3) & 0xF8; uint8_t v21 = (yuv22 << 3) & 0xF8; uint8_t v2 = (v20 +v21) /2; *pu++ = (u1 + u2) /2; *pv++ = (v1 + v2) /2; } in1 = in2; py1 = py2; } } /* * convert yuvp (packed) to yuv420 planar (yu12) * args: * out: pointer to output buffer (yu12) * in: pointer to input buffer containing yuvp (yuv-5-6-5) packed data frame * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void yuvp_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); int w = 0, h = 0; uint8_t *in1 = in; //first line uint8_t *in2 = in1 + (width * 2); //second line uint8_t *py1 = out; // first line uint8_t *py2 = py1 + width; //second line uint8_t *pu = py1 + (width * height); uint8_t *pv = pu + ((width * height) / 4); for(h = 0; h < height; h+=2) { in2 = in1 + (width * 2); py2 = py1 + width; for(w = 0; w < (width*2); w+=4) { uint8_t yuv10 = *in1++; uint8_t yuv11 = *in1++; uint8_t yuv12 = *in1++; uint8_t yuv13 = *in1++; uint8_t yuv20 = *in2++; uint8_t yuv21 = *in2++; uint8_t yuv22 = *in2++; uint8_t yuv23 = *in2++; *py1++ = (uint8_t) yuv11 & 0xF8; *py1++ = (uint8_t) yuv13 & 0xF8; *py2++ = (uint8_t) yuv21 & 0xF8; *py2++ = (uint8_t) yuv23 & 0xF8; uint8_t u10 = ((yuv10 >> 3) & 0x1C) | ((yuv11 << 5) & 0xE0); uint8_t u11 = ((yuv12 >> 3) & 0x1C) | ((yuv13 << 5) & 0xE0); uint8_t u1 = (u10 + u11) /2; uint8_t v10 = (yuv10 << 3) & 0xF8; uint8_t v11 = (yuv12 << 3) & 0xF8; uint8_t v1 = (v10 + v11) /2; uint8_t u20 = ((yuv20 >> 3) & 0x1C) | ((yuv21 << 5) & 0xE0); uint8_t u21 = ((yuv22 >> 3) & 0x1C) | ((yuv23 << 5) & 0xE0); uint8_t u2 = (u20 + u21) /2; uint8_t v20 = (yuv20 << 3) & 0xF8; uint8_t v21 = (yuv22 << 3) & 0xF8; uint8_t v2 = (v20 +v21) /2; *pu++ = (u1 + u2) /2; *pv++ = (v1 + v2) /2; } in1 = in2; py1 = py2; } } /* * convert yuv4 (packed) to yuv420 planar (yu12) * args: * out: pointer to output buffer (yu12) * in: pointer to input buffer containing yuv4 (yuv32) packed data frame * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void yuv4_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); int w = 0, h = 0; uint8_t *in1 = in; //first line uint8_t *in2 = in1 + (width * 4); //second line uint8_t *py1 = out; // first line uint8_t *py2 = py1 + width; //second line uint8_t *pu = py1 + (width * height); uint8_t *pv = pu + ((width * height) / 4); for(h = 0; h < height; h+=2) { in2 = in1 + (width * 4); py2 = py1 + width; for(w = 0; w < (width*4); w+=8) { in1++; //alpha 10 *py1++ = *in1++; //y10 uint8_t u10 = *in1++; //u10 uint8_t v10 = *in1++; //v10 in1++; //alpha 11 *py1++ = *in1++; //y11 uint8_t u11 = *in1++; //u11 uint8_t v11 = *in1++; //v11 in2++; //alpha 20 *py2++ = *in2++; //y20 uint8_t u20 = *in2++; //u20 uint8_t v20 = *in2++; //v20 in2++; //alpha 21 *py2++ = *in2++; //y21 uint8_t u21 = *in2++; //u21 uint8_t v21 = *in2++; //v21 uint8_t u1 = (u10 + u11) /2; uint8_t v1 = (v10 + v11) /2; uint8_t u2 = (u20 + u21) /2; uint8_t v2 = (v20 + v21) /2; *pu++ = (u1 + u2) /2; *pv++ = (v1 + v2) /2; } in1 = in2; py1 = py2; } } /* *convert from 420 planar (yv12) to 420 planar (yu12) * args: * out - pointer to output yu12 planar data buffer * in - pointer to input yv12 planar data buffer * width - frame width * height - frame height * * asserts: * in is not null * out is not null * * returns: none */ void yv12_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); /*copy y data*/ memcpy(out, in, width*height); /*copy u data*/ memcpy(out+(width*height), in+((width * height * 5) / 4), width * height / 4); /*copy v data*/ memcpy(out+((width * height * 5) / 4), in+(width * height), width * height / 4); } /* * convert nv12 planar (uv interleaved) to yuv420 planar (yu12) * args: * out: pointer to output buffer (yu12) * in: pointer to input buffer containing nv12 planar data frame * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void nv12_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); /*copy y data*/ memcpy(out, in, width*height); uint8_t *puv = in + (width * height); uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height) / 4); /*uv plane*/ int i = 0; for(i=0; i< width * height /2; i+=2) { *pu++ = *puv++; *pv++ = *puv++; } } /* * convert nv21 planar (vu interleaved) to yuv420 planar (yu12) * args: * out: pointer to output buffer (yu12) * in: pointer to input buffer containing nv21 planar data frame * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void nv21_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); /*copy y data*/ memcpy(out, in, width*height); uint8_t *puv = in + (width * height); uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height) / 4); /*uv plane*/ int i = 0; for(i=0; i< width * height /2; i+=2) { *pv++ = *puv++; *pu++ = *puv++; } } /* * convert yuv 422 planar (uv interleaved) (nv16) to yuv420 planar (yu12) * args: * out: pointer to output buffer (yu12) * in: pointer to input buffer containing yuv422 (nv16) planar data frame * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void nv16_to_yu12 (uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); /*copy y data*/ memcpy(out, in, width*height); //uv plane uint8_t *puv1 = in + (width * height); //first line uint8_t *puv2 = puv1 + width; //second line uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height) / 4); int h = 0; int w = 0; for(h=0; h < height; h+=2) { puv2 = puv1 + width; for(w=0; w < width; w+=2) { *pu++ = ((*puv1++) + (*puv2++)) / 2; //average *pv++ = ((*puv1++) + (*puv2++)) / 2; //average } puv1 = puv2; } } /* * convert yuv 422 planar (vu interleaved) (nv61) to yuv420 planar (yu12) * args: * out: pointer to output buffer (yu12) * in: pointer to input buffer containing yuv422 (nv61) planar data frame * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void nv61_to_yu12 (uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); /*copy y data*/ memcpy(out, in, width*height); /*uv plane*/ uint8_t *puv1 = in + (width * height); //first line uint8_t *puv2 = puv1 + width; //second line uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height) / 4); int h = 0; int w = 0; for(h=0; h < height; h+=2) { puv2 = puv1 + width; for(w=0; w < width; w+=2) { *pv++ = ((*puv1++) + (*puv2++)) / 2; //average *pu++ = ((*puv1++) + (*puv2++)) / 2; //average } puv1 = puv2; } } /* * convert yuv444 planar (uv interleaved) (nv24) to yuv420 planar (yu12) * args: * out: pointer to output buffer (yu12) * in: pointer to input buffer containing nv24 planar data frame * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void nv24_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); /*copy y data*/ memcpy(out, in, width*height); //uv plane uint8_t *puv1 = in + (width * height); //first line uint8_t *puv2 = puv1 + (width * 2); //second line uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height) / 4); int h = 0; int w = 0; for(h=0; h < height; h+=2) { puv2 = puv1 + (width * 2); for(w=0; w < (width * 2); w+=4) { uint8_t u1 = ((*puv1++) + (*puv2++)) / 2; uint8_t v1 = ((*puv1++) + (*puv2++)) / 2; uint8_t u2 = ((*puv1++) + (*puv2++)) / 2; uint8_t v2 = ((*puv1++) + (*puv2++)) / 2; *pu++ = (u1 + u2)/2; //average *pv++ = (v1 + v2)/2; //average } puv1 = puv2; } } /* * convert yuv444 planar (uv interleaved) (nv42) to yuv420 planar (yu12) * args: * out: pointer to output buffer (yu12) * in: pointer to input buffer containing nv42 planar data frame * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void nv42_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); /*copy y data*/ memcpy(out, in, width*height); //uv plane uint8_t *puv1 = in + (width * height); //first line uint8_t *puv2 = puv1 + (width * 2); //second line uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height) / 4); int h = 0; int w = 0; for(h=0; h < height; h+=2) { puv2 = puv1 + (width * 2); for(w=0; w < (width * 2); w+=4) { uint8_t v1 = ((*puv1++) + (*puv2++)) / 2; uint8_t u1 = ((*puv1++) + (*puv2++)) / 2; uint8_t v2 = ((*puv1++) + (*puv2++)) / 2; uint8_t u2 = ((*puv1++) + (*puv2++)) / 2; *pu++ = (u1 + u2)/2; //average *pv++ = (v1 + v2)/2; //average } puv1 = puv2; } } /* * Unpack buffer of (vw bit) data into padded 16bit buffer. * args: * raw - pointer to input raw packed data buffer * unpacked - pointer to unpacked output data buffer * vw - vw bit * unpacked_len - length * * asserts: * none * * returns: none */ static inline void convert_packed_to_16bit(uint8_t *raw, uint16_t *unpacked, int vw, int unpacked_len) { int mask = (1 << vw) - 1; uint32_t buffer = 0; int bitsIn = 0; while (unpacked_len--) { while (bitsIn < vw) { buffer = (buffer << 8) | *(raw++); bitsIn += 8; } bitsIn -= vw; *(unpacked++) = (buffer >> bitsIn) & mask; } } /* * convert y10b (bit-packed array greyscale format) to yu12 * args: * out: pointer to output buffer (yu12) * in: pointer to input buffer containing y10b (bit-packed array) data frame * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void y10b_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); uint16_t *unpacked_buffer = NULL; uint16_t *ptmp; uint8_t *py = out; uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height) / 4); int h = 0; unpacked_buffer = malloc(width * height * sizeof(uint16_t)); if (unpacked_buffer == NULL) { fprintf(stderr, "V4L2_CORE: FATAL memory allocation failure (y10b_to_yu12): %s\n", strerror(errno)); exit(-1); } convert_packed_to_16bit(in, unpacked_buffer, 10, width * height); ptmp = unpacked_buffer; for (h = 0; h < height; h++) { int w=0; for (w = 0; w < width; w++) { /* Y */ *py++ = (uint8_t) ((*ptmp++ & 0x3FF) >> 2); } } for(h=0; h < (width * height / 4); h++) { /* U */ *pu++ = 0x80; /* V */ *pv++ = 0x80; } free(unpacked_buffer); } /* * convert yuv 411 packed (y41p) to planar yuv 420 (yu12) * args: * out: pointer to output buffer (yu12) * in: pointer to input buffer containing y41p data frame * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void y41p_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); uint8_t *py1 = out; uint8_t *py2 = out + width; uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height) / 4); int h=0; int linesize = width * 3 /2; for(h = 0; h < height; h += 2) { py1 = out + (h * width); // first line py2 = out + ((h + 1) * width); // second line int offset1 = linesize * h; //line 1 int offset2 = linesize * (h + 1); //line 2 int w = 0; for(w = 0; w < linesize; w += 12) { /* y first line */ *py1++ = in[w + 1 + offset1]; //Y00 *py1++ = in[w + 3 + offset1]; //Y01 *py1++ = in[w + 5 + offset1]; //Y02 *py1++ = in[w + 7 + offset1]; //Y03 *py1++ = in[w + 8 + offset1]; //Y04 *py1++ = in[w + 9 + offset1]; //Y05 *py1++ = in[w + 10 + offset1]; //Y06 *py1++ = in[w + 11 + offset1]; //Y07 /* y second line */ *py2++ = in[w + 1 + offset2]; //Y10 *py2++ = in[w + 3 + offset2]; //Y11 *py2++ = in[w + 5 + offset2]; //Y12 *py2++ = in[w + 7 + offset2]; //Y13 *py2++ = in[w + 8 + offset2]; //Y14 *py2++ = in[w + 9 + offset2]; //Y15 *py2++ = in[w + 10 + offset2]; //Y16 *py2++ = in[w + 11 + offset2]; //Y17 /*U0 and U1 average first and second lines*/ *pu++ = (in[w + offset1] + in[w + offset2]) / 2; //U00 + U10 /2 *pu++ = (in[w + offset1] + in[w + offset2]) / 2; //U00 + U10 /2 /*U2 and U3 average first and second lines*/ *pu++ = (in[w + 4 + offset1] + in[w + 4 + offset2]) / 2; //U01 + U11 /2 *pu++ = (in[w + 4 + offset1] + in[w + 4 + offset2]) / 2; //U01 + U11 /2 /*V0 and V1 average first and second lines*/ *pv++ = (in[w + 2 + offset1] + in[w + 2 + offset2]) / 2; //V00 + V10 /2 *pv++ = (in[w + 2 + offset1] + in[w + 2 + offset2]) / 2; //V00 + V10 /2 /*V2 and V3 average first and second lines*/ *pv++ = (in[w + 6 + offset1] + in[w + 6 + offset2]) / 2; //V01 + V11 /2 *pv++ = (in[w + 6 + offset1] + in[w + 6 + offset2]) / 2; //V01 + V11 /2 } } } /* * convert yuv mono (grey) to yuv 420 planar (yu12) * args: * out: pointer to output buffer (yu12) * in: pointer to input buffer containing grey (y only) data frame * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void grey_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height) / 4); int h=0; /* Y */ memcpy(out, in, width * height); /* U and V */ for (h=0; h < (width * height / 4); h++) { *pu++ = 0x80; *pv++ = 0x80; } } /* * convert y16 (16 bit greyscale format) to yu12 * args: * out: pointer to output buffer (yu12) * in: pointer to input buffer containing y16 (16 bit greyscale) data frame * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void y16_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); uint16_t *ptmp = (uint16_t *) in; uint8_t *py = out; uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height) / 4); int h = 0; for (h = 0; h < height; h++) { int w=0; for (w = 0; w < width; w++) { /* Y */ *py++ = (uint8_t) ((*ptmp++ & 0xFF00) >> 8); } } for(h=0; h < (width * height / 4); h++) { /* U */ *pu++ = 0x80; /* V */ *pv++ = 0x80; } } /* * convert y16x (16 bit greyscale format - be) to yu12 * args: * out: pointer to output buffer (yu12) * in: pointer to input buffer containing y16x (16 bit greyscale bigendian) data frame * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void y16x_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); uint16_t *ptmp = (uint16_t *) in; uint8_t *py = out; uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height) / 4); int h = 0; for (h = 0; h < height; h++) { int w=0; for (w = 0; w < width; w++) { /* Y */ *py++ = (uint8_t) (*ptmp++ & 0x00FF); } } for(h=0; h < (width * height / 4); h++) { /* U */ *pu++ = 0x80; /* V */ *pv++ = 0x80; } } /* * convert SPCA501 (s501) to yuv 420 planar (yu12) * s501 |Y0..width..Y0|U..width/2..U|Y1..width..Y1|V..width/2..V| * signed values (-128;+127) must be converted to unsigned (0; 255) * args: * out: pointer to output buffer (yu12) * in: pointer to input buffer containing s501 data frame * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void s501_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); /*assertions*/ assert(in); assert(out); int h = 0; int8_t *pin = (int8_t *) in; uint8_t *py = out; uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height ) / 4); for (h = 0; h < height; h += 2 ) { int w = 0; /* Y */ for (w = 0; w < width; w++) { *py++ = (uint8_t) 0x80 + *pin++; } /* U */ for (w = 0; w < width /2; w++) { *pu++ = (uint8_t) 0x80 + *pin++; } /* Y */ for (w = 0; w < width; w++) { *py++ = (uint8_t) 0x80 + *pin++; } /* V */ for (w = 0; w < width /2; w++) { *pv++ = (uint8_t) 0x80 + *pin++; } } } /* * convert SPCA505 (s505) to yuv 420 planar (yu12) * s505 |Y0..width..Y0|Y1..width..Y1|U..width/2..U|V..width/2..V| * signed values (-128;+127) must be converted to unsigned (0; 255) * args: * out: pointer to output buffer (yu12) * in: pointer to input buffer containing s501 data frame * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void s505_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); int h = 0; int8_t *pin = (int8_t *) in; uint8_t *py = out; uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height ) / 4); for (h = 0; h < height; h += 2 ) { int w = 0; /* Y */ for (w = 0; w < width * 2; w++) // 2 lines { *py++ = (uint8_t) 0x80 + *pin++; } /* U */ for (w = 0; w < width /2; w++) { *pu++ = (uint8_t) 0x80 + *pin++; } /* V */ for (w = 0; w < width /2; w++) { *pv++ = (uint8_t) 0x80 + *pin++; } } } /* * convert SPCA508 (s508) to yuv 420 planar (yu12) * s508 |Y0..width..Y0|U..width/2..U|V..width/2..V|Y1..width..Y1| * signed values (-128;+127) must be converted to unsigned (0; 255) * args: * out: pointer to output buffer (yu12) * in: pointer to input buffer containing s501 data frame * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void s508_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(in); assert(out); int h = 0; int8_t *pin = (int8_t *) in; uint8_t *py = out; uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height ) / 4); for (h = 0; h < height; h += 2 ) { int w = 0; /* Y */ for (w = 0; w < width; w++) { *py++ = (uint8_t) 0x80 + *pin++; } /* U */ for (w = 0; w < width /2; w++) { *pu++ = (uint8_t) 0x80 + *pin++; } /* V */ for (w = 0; w < width /2; w++) { *pv++ = (uint8_t) 0x80 + *pin++; } /* Y */ for (w = 0; w < width; w++) { *py++ = (uint8_t) 0x80 + *pin++; } } } /* * convert rgb24 to yu12 * args: * out: pointer to output buffer containing yu12 data * in: pointer to input buffer containing rgb24 data * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void rgb24_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(out); assert(in); uint8_t *py = out; uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height) / 4); uint8_t *in1 = in; //first line uint8_t *in2 = in + (width * 3); //second line int i=0; for(i = 0; i < (width * height * 3); i += 3) { /* y */ *py++ =CLIP(0.299 * (in1[i] - 128) + 0.587 * (in1[i+1] - 128) + 0.114 * (in1[i+2] - 128) + 128); } int h = 0; for(h = 0; h < height; h += 2) { in1 = in + (h * width * 3); in2 = in1 + (width * 3); for(i = 0; i < (width * 3); i += 6) { /* u v */ uint8_t u1 = CLIP(((- 0.147 * (in1[i] - 128) - 0.289 * (in1[i+1] - 128) + 0.436 * (in1[i+2] - 128) + 128) + (- 0.147 * (in1[i+3] - 128) - 0.289 * (in1[i+4] - 128) + 0.436 * (in1[i+5] - 128) + 128))/2); uint8_t v1 =CLIP(((0.615 * (in1[i] - 128) - 0.515 * (in1[i+1] - 128) - 0.100 * (in1[i+2] - 128) + 128) + (0.615 * (in1[i+3] - 128) - 0.515 * (in1[i+4] - 128) - 0.100 * (in1[i+5] - 128) + 128))/2); uint8_t u2 = CLIP(((- 0.147 * (in2[i] - 128) - 0.289 * (in2[i+1] - 128) + 0.436 * (in2[i+2] - 128) + 128) + (- 0.147 * (in2[i+3] - 128) - 0.289 * (in2[i+4] - 128) + 0.436 * (in2[i+5] - 128) + 128))/2); uint8_t v2 =CLIP(((0.615 * (in2[i] - 128) - 0.515 * (in2[i+1] - 128) - 0.100 * (in2[i+2] - 128) + 128) + (0.615 * (in2[i+3] - 128) - 0.515 * (in2[i+4] - 128) - 0.100 * (in2[i+5] - 128) + 128))/2); *pu++ = (u1 + u2) / 2; *pv++ = (v1 + v2) / 2; } } } /* * convert bgr24 to yu12 * args: * out: pointer to output buffer containing yu12 data * in: pointer to input buffer containing bgr24 data * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void bgr24_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(out); assert(in); uint8_t *py = out; uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height) / 4); uint8_t *in1 = in; //first line uint8_t *in2 = in + (width * 3); //second line int i = 0; for(i = 0; i < (width * height * 3); i += 3) { /* y */ *py++ =CLIP(0.299 * (in1[i+2] - 128) + 0.587 * (in1[i+1] - 128) + 0.114 * (in1[i] - 128) + 128); } int h = 0; for(h = 0; h < height; h += 2) { in1 = in + (h * width * 3); in2 = in1 + (width * 3); for(i = 0; i < (width * 3); i += 6) { /* u */ uint8_t u1 = CLIP(((- 0.147 * (in1[i+2] - 128) - 0.289 * (in1[i+1] - 128) + 0.436 * (in1[i] - 128) + 128) + (- 0.147 * (in1[i+5] - 128) - 0.289 * (in1[i+4] - 128) + 0.436 * (in1[i+3] - 128) + 128))/2); uint8_t u2 = CLIP(((- 0.147 * (in2[i+2] - 128) - 0.289 * (in2[i+1] - 128) + 0.436 * (in2[i] - 128) + 128) + (- 0.147 * (in2[i+5] - 128) - 0.289 * (in2[i+4] - 128) + 0.436 * (in2[i+3] - 128) + 128))/2); /* v*/ uint8_t v1 =CLIP(((0.615 * (in1[i+2] - 128) - 0.515 * (in1[i+1] - 128) - 0.100 * (in1[i] - 128) + 128) + (0.615 * (in1[i+5] - 128) - 0.515 * (in1[i+4] - 128) - 0.100 * (in1[i+3] - 128) + 128))/2); uint8_t v2 =CLIP(((0.615 * (in2[i+2] - 128) - 0.515 * (in2[i+1] - 128) - 0.100 * (in2[i] - 128) + 128) + (0.615 * (in2[i+5] - 128) - 0.515 * (in2[i+4] - 128) - 0.100 * (in2[i+3] - 128) + 128))/2); *pu++ = (u1 + u2) / 2; *pv++ = (v1 + v2) / 2; } } } /* * convert rgb1 (rgb332) to yu12 * args: * out: pointer to output buffer containing yu12 data * in: pointer to input buffer containing rgb332 data * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void rgb1_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(out); assert(in); uint8_t *py1 = out;//first line uint8_t *py2 = py1 + width;//second line uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height) / 4); uint8_t *in1 = in; //first line uint8_t *in2 = in + width; //second line (1 byte per pixel) int h = 0; int w = 0; for(h = 0; h < height; h += 2) { in2 = in1 + width; py2 = py1 + width; for(w = 0; w < width; w +=2) { uint8_t px00 = *in1++; uint8_t r00 = px00 & 0xE0; uint8_t g00 = (px00 << 3) & 0xE0; uint8_t b00 = (px00 << 6) & 0xC0; /* y */ *py1++ = CLIP(0.299 * (r00 - 128) + 0.587 * (g00 - 128) + 0.114 * (b00 - 128) + 128); uint8_t px01 = *in1++; uint8_t r01 = px01 & 0xE0; uint8_t g01 = (px01 << 3) & 0xE0; uint8_t b01 = (px01 << 6) & 0xC0; /* y */ *py1++ = CLIP(0.299 * (r01 - 128) + 0.587 * (g01 - 128) + 0.114 * (b01 - 128) + 128); uint8_t px10 = *in2++; uint8_t r10 = px10 & 0xE0; uint8_t g10 = (px10 << 3) & 0xE0; uint8_t b10 = (px10 << 6) & 0xC0; /* y */ *py2++ = CLIP(0.299 * (r10 - 128) + 0.587 * (g10 - 128) + 0.114 * (b10 - 128) + 128); uint8_t px11 = *in2++; uint8_t r11 = px11 & 0xE0; uint8_t g11 = (px11 << 3) & 0xE0; uint8_t b11 = (px11 << 6) & 0xC0; /* y */ *py2++ = CLIP(0.299 * (r11 - 128) + 0.587 * (g11 - 128) + 0.114 * (b11 - 128) + 128); /* u v */ uint8_t u1 = CLIP(((- 0.147 * (r00 - 128) - 0.289 * (g00 - 128) + 0.436 * (b00 - 128) + 128) + (- 0.147 * (r01 - 128) - 0.289 * (g01 - 128) + 0.436 * (b01 - 128) + 128))/2); uint8_t v1 =CLIP(((0.615 * (r00 - 128) - 0.515 * (g00 - 128) - 0.100 * (b00 - 128) + 128) + (0.615 * (r01 - 128) - 0.515 * (g01 - 128) - 0.100 * (b01 - 128) + 128))/2); uint8_t u2 = CLIP(((- 0.147 * (r10 - 128) - 0.289 * (g10 - 128) + 0.436 * (b10 - 128) + 128) + (- 0.147 * (r11 - 128) - 0.289 * (g11 - 128) + 0.436 * (b11 - 128) + 128))/2); uint8_t v2 =CLIP(((0.615 * (r10 - 128) - 0.515 * (g10 - 128) - 0.100 * (b10 - 128) + 128) + (0.615 * (r11 - 128) - 0.515 * (g11 - 128) - 0.100 * (b11 - 128) + 128))/2); *pu++ = (u1 + u2) / 2; *pv++ = (v1 + v2) / 2; } in1 = in2; py1 = py2; } } /* * convert ar12 (argb444) to yu12 * args: * out: pointer to output buffer containing yu12 data * in: pointer to input buffer containing argb444 data * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void ar12_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(out); assert(in); uint8_t *py1 = out;//first line uint8_t *py2 = py1 + width;//second line uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height) / 4); uint8_t *in1 = in; //first line uint8_t *in2 = in + (width * 2); //second line (2 byte per pixel) int h = 0; int w = 0; for(h = 0; h < height; h += 2) { in2 = in1 + (width * 2); py2 = py1 + width; for(w = 0; w < (width * 2); w +=4) { uint8_t px000 = *in1++; uint8_t px001 = *in1++; uint8_t r00 = (px001 << 4) & 0xF0; uint8_t g00 = px000 & 0xF0; uint8_t b00 = (px000 << 4) & 0xF0; /* y */ *py1++ = CLIP(0.299 * (r00 - 128) + 0.587 * (g00 - 128) + 0.114 * (b00 - 128) + 128); uint8_t px010 = *in1++; uint8_t px011 = *in1++; uint8_t r01 = (px011 << 4) & 0xF0; uint8_t g01 = px010 & 0xF0; uint8_t b01 = (px010 << 4) & 0xF0; /* y */ *py1++ = CLIP(0.299 * (r01 - 128) + 0.587 * (g01 - 128) + 0.114 * (b01 - 128) + 128); uint8_t px100 = *in2++; uint8_t px101 = *in2++; uint8_t r10 = (px101 << 4) & 0xF0; uint8_t g10 = px100 & 0xF0; uint8_t b10 = (px100 << 4) & 0xF0; /* y */ *py2++ = CLIP(0.299 * (r10 - 128) + 0.587 * (g10 - 128) + 0.114 * (b10 - 128) + 128); uint8_t px110 = *in2++; uint8_t px111 = *in2++; uint8_t r11 = (px111 << 4) & 0xF0; uint8_t g11 = px110 & 0xF0; uint8_t b11 = (px110 << 4) & 0xF0; /* y */ *py2++ = CLIP(0.299 * (r11 - 128) + 0.587 * (g11 - 128) + 0.114 * (b11 - 128) + 128); /* u v */ uint8_t u1 = CLIP(((- 0.147 * (r00 - 128) - 0.289 * (g00 - 128) + 0.436 * (b00 - 128) + 128) + (- 0.147 * (r01 - 128) - 0.289 * (g01 - 128) + 0.436 * (b01 - 128) + 128))/2); uint8_t v1 =CLIP(((0.615 * (r00 - 128) - 0.515 * (g00 - 128) - 0.100 * (b00 - 128) + 128) + (0.615 * (r01 - 128) - 0.515 * (g01 - 128) - 0.100 * (b01 - 128) + 128))/2); uint8_t u2 = CLIP(((- 0.147 * (r10 - 128) - 0.289 * (g10 - 128) + 0.436 * (b10 - 128) + 128) + (- 0.147 * (r11 - 128) - 0.289 * (g11 - 128) + 0.436 * (b11 - 128) + 128))/2); uint8_t v2 =CLIP(((0.615 * (r10 - 128) - 0.515 * (g10 - 128) - 0.100 * (b10 - 128) + 128) + (0.615 * (r11 - 128) - 0.515 * (g11 - 128) - 0.100 * (b11 - 128) + 128))/2); *pu++ = (u1 + u2) / 2; *pv++ = (v1 + v2) / 2; } in1 = in2; py1 = py2; } } /* * convert ar15 (argb555) to yu12 * args: * out: pointer to output buffer containing yu12 data * in: pointer to input buffer containing argb555 data * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void ar15_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(out); assert(in); uint8_t *py1 = out;//first line uint8_t *py2 = py1 + width;//second line uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height) / 4); uint8_t *in1 = in; //first line uint8_t *in2 = in + (width * 2); //second line (2 byte per pixel) int h = 0; int w = 0; for(h = 0; h < height; h += 2) { in2 = in1 + (width * 2); py2 = py1 + width; for(w = 0; w < (width * 2); w +=4) { uint8_t px000 = *in1++; uint8_t px001 = *in1++; uint8_t r00 = (px001 << 1) & 0xF8; uint8_t g00 = ((px001 << 6) & 0xC0) | ((px000 >> 2) & 0x38); uint8_t b00 = (px000 << 3) & 0xF8; /* y */ *py1++ = CLIP(0.299 * (r00 - 128) + 0.587 * (g00 - 128) + 0.114 * (b00 - 128) + 128); uint8_t px010 = *in1++; uint8_t px011 = *in1++; uint8_t r01 = (px011 << 1) & 0xF8; uint8_t g01 = ((px011 << 6) & 0xC0) | ((px010 >> 2) & 0x38); uint8_t b01 = (px010 << 3) & 0xF8; /* y */ *py1++ = CLIP(0.299 * (r01 - 128) + 0.587 * (g01 - 128) + 0.114 * (b01 - 128) + 128); uint8_t px100 = *in2++; uint8_t px101 = *in2++; uint8_t r10 = (px101 << 1) & 0xF8; uint8_t g10 = ((px101 << 6) & 0xC0) | ((px100 >> 2) & 0x38); uint8_t b10 = (px100 << 3) & 0xF8; /* y */ *py2++ = CLIP(0.299 * (r10 - 128) + 0.587 * (g10 - 128) + 0.114 * (b10 - 128) + 128); uint8_t px110 = *in2++; uint8_t px111 = *in2++; uint8_t r11 = (px111 << 1) & 0xF8; uint8_t g11 = ((px111 << 6) & 0xC0) | ((px110 >> 2) & 0x38); uint8_t b11 = (px110 << 3) & 0xF8; /* y */ *py2++ = CLIP(0.299 * (r11 - 128) + 0.587 * (g11 - 128) + 0.114 * (b11 - 128) + 128); /* u v */ uint8_t u1 = CLIP(((- 0.147 * (r00 - 128) - 0.289 * (g00 - 128) + 0.436 * (b00 - 128) + 128) + (- 0.147 * (r01 - 128) - 0.289 * (g01 - 128) + 0.436 * (b01 - 128) + 128))/2); uint8_t v1 =CLIP(((0.615 * (r00 - 128) - 0.515 * (g00 - 128) - 0.100 * (b00 - 128) + 128) + (0.615 * (r01 - 128) - 0.515 * (g01 - 128) - 0.100 * (b01 - 128) + 128))/2); uint8_t u2 = CLIP(((- 0.147 * (r10 - 128) - 0.289 * (g10 - 128) + 0.436 * (b10 - 128) + 128) + (- 0.147 * (r11 - 128) - 0.289 * (g11 - 128) + 0.436 * (b11 - 128) + 128))/2); uint8_t v2 =CLIP(((0.615 * (r10 - 128) - 0.515 * (g10 - 128) - 0.100 * (b10 - 128) + 128) + (0.615 * (r11 - 128) - 0.515 * (g11 - 128) - 0.100 * (b11 - 128) + 128))/2); *pu++ = (u1 + u2) / 2; *pv++ = (v1 + v2) / 2; } in1 = in2; py1 = py2; } } /* * convert ar15_be (argb555X) to yu12 * args: * out: pointer to output buffer containing yu12 data * in: pointer to input buffer containing argb555X (be) data * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void ar15x_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(out); assert(in); uint8_t *py1 = out;//first line uint8_t *py2 = py1 + width;//second line uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height) / 4); uint8_t *in1 = in; //first line uint8_t *in2 = in + (width * 2); //second line (2 byte per pixel) int h = 0; int w = 0; for(h = 0; h < height; h += 2) { in2 = in1 + (width * 2); py2 = py1 + width; for(w = 0; w < (width * 2); w +=4) { uint8_t px000 = *in1++; uint8_t px001 = *in1++; uint8_t r00 = (px000 << 1) & 0xF8; uint8_t g00 = ((px000 << 6) & 0xC0) | ((px001 >> 2) & 0x38); uint8_t b00 = (px001 << 3) & 0xF8; /* y */ *py1++ = CLIP(0.299 * (r00 - 128) + 0.587 * (g00 - 128) + 0.114 * (b00 - 128) + 128); uint8_t px010 = *in1++; uint8_t px011 = *in1++; uint8_t r01 = (px010 << 1) & 0xF8; uint8_t g01 = ((px010 << 6) & 0xC0) | ((px011 >> 2) & 0x38); uint8_t b01 = (px011 << 3) & 0xF8; /* y */ *py1++ = CLIP(0.299 * (r01 - 128) + 0.587 * (g01 - 128) + 0.114 * (b01 - 128) + 128); uint8_t px100 = *in2++; uint8_t px101 = *in2++; uint8_t r10 = (px100 << 1) & 0xF8; uint8_t g10 = ((px100 << 6) & 0xC0) | ((px101 >> 2) & 0x38); uint8_t b10 = (px101 << 3) & 0xF8; /* y */ *py2++ = CLIP(0.299 * (r10 - 128) + 0.587 * (g10 - 128) + 0.114 * (b10 - 128) + 128); uint8_t px110 = *in2++; uint8_t px111 = *in2++; uint8_t r11 = (px110 << 1) & 0xF8; uint8_t g11 = ((px110 << 6) & 0xC0) | ((px111 >> 2) & 0x38); uint8_t b11 = (px111 << 3) & 0xF8; /* y */ *py2++ = CLIP(0.299 * (r11 - 128) + 0.587 * (g11 - 128) + 0.114 * (b11 - 128) + 128); /* u v */ uint8_t u1 = CLIP(((- 0.147 * (r00 - 128) - 0.289 * (g00 - 128) + 0.436 * (b00 - 128) + 128) + (- 0.147 * (r01 - 128) - 0.289 * (g01 - 128) + 0.436 * (b01 - 128) + 128))/2); uint8_t v1 =CLIP(((0.615 * (r00 - 128) - 0.515 * (g00 - 128) - 0.100 * (b00 - 128) + 128) + (0.615 * (r01 - 128) - 0.515 * (g01 - 128) - 0.100 * (b01 - 128) + 128))/2); uint8_t u2 = CLIP(((- 0.147 * (r10 - 128) - 0.289 * (g10 - 128) + 0.436 * (b10 - 128) + 128) + (- 0.147 * (r11 - 128) - 0.289 * (g11 - 128) + 0.436 * (b11 - 128) + 128))/2); uint8_t v2 =CLIP(((0.615 * (r10 - 128) - 0.515 * (g10 - 128) - 0.100 * (b10 - 128) + 128) + (0.615 * (r11 - 128) - 0.515 * (g11 - 128) - 0.100 * (b11 - 128) + 128))/2); *pu++ = (u1 + u2) / 2; *pv++ = (v1 + v2) / 2; } in1 = in2; py1 = py2; } } /* * convert rgbp (rgb565) to yu12 * args: * out: pointer to output buffer containing yu12 data * in: pointer to input buffer containing argb555 data * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void rgbp_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(out); assert(in); uint8_t *py1 = out;//first line uint8_t *py2 = py1 + width;//second line uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height) / 4); uint8_t *in1 = in; //first line uint8_t *in2 = in + (width * 2); //second line (2 byte per pixel) int h = 0; int w = 0; for(h = 0; h < height; h += 2) { in2 = in1 + (width * 2); py2 = py1 + width; for(w = 0; w < (width * 2); w +=4) { uint8_t px000 = *in1++; uint8_t px001 = *in1++; uint8_t r00 = px001 & 0xF8; uint8_t g00 = ((px001 << 5) & 0xE0) | ((px000 >> 3) & 0x1C); uint8_t b00 = (px000 << 3) & 0xF8; /* y */ *py1++ = CLIP(0.299 * (r00 - 128) + 0.587 * (g00 - 128) + 0.114 * (b00 - 128) + 128); uint8_t px010 = *in1++; uint8_t px011 = *in1++; uint8_t r01 = px011 & 0xF8; uint8_t g01 = ((px011 << 5) & 0xE0) | ((px010 >> 3) & 0x1C); uint8_t b01 = (px010 << 3) & 0xF8; /* y */ *py1++ = CLIP(0.299 * (r01 - 128) + 0.587 * (g01 - 128) + 0.114 * (b01 - 128) + 128); uint8_t px100 = *in2++; uint8_t px101 = *in2++; uint8_t r10 = px101 & 0xF8; uint8_t g10 = ((px101 << 5) & 0xE0) | ((px100 >> 3) & 0x1C); uint8_t b10 = (px100 << 3) & 0xF8; /* y */ *py2++ = CLIP(0.299 * (r10 - 128) + 0.587 * (g10 - 128) + 0.114 * (b10 - 128) + 128); uint8_t px110 = *in2++; uint8_t px111 = *in2++; uint8_t r11 = px111 & 0xF8; uint8_t g11 = ((px111 << 5) & 0xE0) | ((px110 >> 3) & 0x1C); uint8_t b11 = (px110 << 3) & 0xF8; /* y */ *py2++ = CLIP(0.299 * (r11 - 128) + 0.587 * (g11 - 128) + 0.114 * (b11 - 128) + 128); /* u v */ uint8_t u1 = CLIP(((- 0.147 * (r00 - 128) - 0.289 * (g00 - 128) + 0.436 * (b00 - 128) + 128) + (- 0.147 * (r01 - 128) - 0.289 * (g01 - 128) + 0.436 * (b01 - 128) + 128))/2); uint8_t v1 =CLIP(((0.615 * (r00 - 128) - 0.515 * (g00 - 128) - 0.100 * (b00 - 128) + 128) + (0.615 * (r01 - 128) - 0.515 * (g01 - 128) - 0.100 * (b01 - 128) + 128))/2); uint8_t u2 = CLIP(((- 0.147 * (r10 - 128) - 0.289 * (g10 - 128) + 0.436 * (b10 - 128) + 128) + (- 0.147 * (r11 - 128) - 0.289 * (g11 - 128) + 0.436 * (b11 - 128) + 128))/2); uint8_t v2 =CLIP(((0.615 * (r10 - 128) - 0.515 * (g10 - 128) - 0.100 * (b10 - 128) + 128) + (0.615 * (r11 - 128) - 0.515 * (g11 - 128) - 0.100 * (b11 - 128) + 128))/2); *pu++ = (u1 + u2) / 2; *pv++ = (v1 + v2) / 2; } in1 = in2; py1 = py2; } } /* * convert rgbr (rgb565X) to yu12 * args: * out: pointer to output buffer containing yu12 data * in: pointer to input buffer containing rgb565 bigendian data * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void rgbr_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(out); assert(in); uint8_t *py1 = out;//first line uint8_t *py2 = py1 + width;//second line uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height) / 4); uint8_t *in1 = in; //first line uint8_t *in2 = in + (width * 2); //second line (2 byte per pixel) int h = 0; int w = 0; for(h = 0; h < height; h += 2) { in2 = in1 + (width * 2); py2 = py1 + width; for(w = 0; w < (width * 2); w +=4) { uint8_t px000 = *in1++; uint8_t px001 = *in1++; uint8_t r00 = px000 & 0xF8; uint8_t g00 = ((px000 << 5) & 0xE0) | ((px001 >> 3) & 0x1C); uint8_t b00 = (px001 << 3) & 0xF8; /* y */ *py1++ = CLIP(0.299 * (r00 - 128) + 0.587 * (g00 - 128) + 0.114 * (b00 - 128) + 128); uint8_t px010 = *in1++; uint8_t px011 = *in1++; uint8_t r01 = px010 & 0xF8; uint8_t g01 = ((px010 << 5) & 0xE0) | ((px011 >> 3) & 0x1C); uint8_t b01 = (px011 << 3) & 0xF8; /* y */ *py1++ = CLIP(0.299 * (r01 - 128) + 0.587 * (g01 - 128) + 0.114 * (b01 - 128) + 128); uint8_t px100 = *in2++; uint8_t px101 = *in2++; uint8_t r10 = px100 & 0xF8; uint8_t g10 = ((px100 << 5) & 0xE0) | ((px101 >> 3) & 0x1C); uint8_t b10 = (px101 << 3) & 0xF8; /* y */ *py2++ = CLIP(0.299 * (r10 - 128) + 0.587 * (g10 - 128) + 0.114 * (b10 - 128) + 128); uint8_t px110 = *in2++; uint8_t px111 = *in2++; uint8_t r11 = px110 & 0xF8; uint8_t g11 = ((px110 << 5) & 0xE0) | ((px111 >> 3) & 0x1C); uint8_t b11 = (px111 << 3) & 0xF8; /* y */ *py2++ = CLIP(0.299 * (r11 - 128) + 0.587 * (g11 - 128) + 0.114 * (b11 - 128) + 128); /* u v */ uint8_t u1 = CLIP(((- 0.147 * (r00 - 128) - 0.289 * (g00 - 128) + 0.436 * (b00 - 128) + 128) + (- 0.147 * (r01 - 128) - 0.289 * (g01 - 128) + 0.436 * (b01 - 128) + 128))/2); uint8_t v1 =CLIP(((0.615 * (r00 - 128) - 0.515 * (g00 - 128) - 0.100 * (b00 - 128) + 128) + (0.615 * (r01 - 128) - 0.515 * (g01 - 128) - 0.100 * (b01 - 128) + 128))/2); uint8_t u2 = CLIP(((- 0.147 * (r10 - 128) - 0.289 * (g10 - 128) + 0.436 * (b10 - 128) + 128) + (- 0.147 * (r11 - 128) - 0.289 * (g11 - 128) + 0.436 * (b11 - 128) + 128))/2); uint8_t v2 =CLIP(((0.615 * (r10 - 128) - 0.515 * (g10 - 128) - 0.100 * (b10 - 128) + 128) + (0.615 * (r11 - 128) - 0.515 * (g11 - 128) - 0.100 * (b11 - 128) + 128))/2); *pu++ = (u1 + u2) / 2; *pv++ = (v1 + v2) / 2; } in1 = in2; py1 = py2; } } /* * convert bgrh to yu12 * args: * out: pointer to output buffer containing yu12 data * in: pointer to input buffer containing bgrh (bgr666) data * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void bgrh_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(out); assert(in); uint8_t *py1 = out;//first line uint8_t *py2 = py1 + width;//second line uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height) / 4); uint8_t *in1 = in; //first line uint8_t *in2 = in + (width * 4); //second line (4 byte per pixel) int h = 0; int w = 0; for(h = 0; h < height; h += 2) { in2 = in1 + (width * 4); py2 = py1 + width; for(w = 0; w < (width * 4); w +=8) { uint8_t px000 = *in1++; uint8_t px001 = *in1++; uint8_t px002 = *in1++; in1++; //last byte has empty data uint8_t r00 = ((px002 >> 4) & 0x0C) | ((px001 << 4) & 0xF0); uint8_t g00 = ((px001 >> 2) & 0x3C) | ((px000 << 6) & 0xC0); uint8_t b00 = px000 & 0xFC; /* y */ *py1++ = CLIP(0.299 * (r00 - 128) + 0.587 * (g00 - 128) + 0.114 * (b00 - 128) + 128); uint8_t px010 = *in1++; uint8_t px011 = *in1++; uint8_t px012 = *in1++; in1++; //last byte has empty data uint8_t r01 = ((px012 >> 4) & 0x0C) | ((px011 << 4) & 0xF0); uint8_t g01 = ((px011 >> 2) & 0x3C) | ((px010 << 6) & 0xC0); uint8_t b01 = px010 & 0xFC; /* y */ *py1++ = CLIP(0.299 * (r01 - 128) + 0.587 * (g01 - 128) + 0.114 * (b01 - 128) + 128); uint8_t px100 = *in2++; uint8_t px101 = *in2++; uint8_t px102 = *in2++; in2++; //last byte has empty data uint8_t r10 = ((px102 >> 4) & 0x0C) | ((px101 << 4) & 0xF0); uint8_t g10 = ((px101 >> 2) & 0x3C) | ((px100 << 6) & 0xC0); uint8_t b10 = px100 & 0xFC; /* y */ *py2++ = CLIP(0.299 * (r10 - 128) + 0.587 * (g10 - 128) + 0.114 * (b10 - 128) + 128); uint8_t px110 = *in2++; uint8_t px111 = *in2++; uint8_t px112 = *in2++; in2++; //last byte has empty data uint8_t r11 = ((px112 >> 4) & 0x0C) | ((px111 << 4) & 0xF0); uint8_t g11 = ((px111 >> 2) & 0x3C) | ((px110 << 6) & 0xC0); uint8_t b11 = px110 & 0xFC; /* y */ *py2++ = CLIP(0.299 * (r11 - 128) + 0.587 * (g11 - 128) + 0.114 * (b11 - 128) + 128); /* u v */ uint8_t u1 = CLIP(((- 0.147 * (r00 - 128) - 0.289 * (g00 - 128) + 0.436 * (b00 - 128) + 128) + (- 0.147 * (r01 - 128) - 0.289 * (g01 - 128) + 0.436 * (b01 - 128) + 128))/2); uint8_t v1 =CLIP(((0.615 * (r00 - 128) - 0.515 * (g00 - 128) - 0.100 * (b00 - 128) + 128) + (0.615 * (r01 - 128) - 0.515 * (g01 - 128) - 0.100 * (b01 - 128) + 128))/2); uint8_t u2 = CLIP(((- 0.147 * (r10 - 128) - 0.289 * (g10 - 128) + 0.436 * (b10 - 128) + 128) + (- 0.147 * (r11 - 128) - 0.289 * (g11 - 128) + 0.436 * (b11 - 128) + 128))/2); uint8_t v2 =CLIP(((0.615 * (r10 - 128) - 0.515 * (g10 - 128) - 0.100 * (b10 - 128) + 128) + (0.615 * (r11 - 128) - 0.515 * (g11 - 128) - 0.100 * (b11 - 128) + 128))/2); *pu++ = (u1 + u2) / 2; *pv++ = (v1 + v2) / 2; } in1 = in2; py1 = py2; } } /* * convert ar24 to yu12 * args: * out: pointer to output buffer containing yu12 data * in: pointer to input buffer containing ar24 (bgr32) data * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void ar24_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(out); assert(in); uint8_t *py1 = out;//first line uint8_t *py2 = py1 + width;//second line uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height) / 4); uint8_t *in1 = in; //first line uint8_t *in2 = in + (width * 4); //second line (4 byte per pixel) int h = 0; int w = 0; for(h = 0; h < height; h += 2) { in2 = in1 + (width * 4); py2 = py1 + width; for(w = 0; w < (width * 4); w +=8) { uint8_t b00 = *in1++; uint8_t g00 = *in1++; uint8_t r00 = *in1++; in1++; //last byte has alpha data /* y */ *py1++ = CLIP(0.299 * (r00 - 128) + 0.587 * (g00 - 128) + 0.114 * (b00 - 128) + 128); uint8_t b01 = *in1++; uint8_t g01 = *in1++; uint8_t r01 = *in1++; in1++; //last byte has alpha data /* y */ *py1++ = CLIP(0.299 * (r01 - 128) + 0.587 * (g01 - 128) + 0.114 * (b01 - 128) + 128); uint8_t b10 = *in2++; uint8_t g10 = *in2++; uint8_t r10 = *in2++; in2++; //last byte has alpha data /* y */ *py2++ = CLIP(0.299 * (r10 - 128) + 0.587 * (g10 - 128) + 0.114 * (b10 - 128) + 128); uint8_t b11 = *in2++; uint8_t g11 = *in2++; uint8_t r11 = *in2++; in2++; //last byte has alpha data /* y */ *py2++ = CLIP(0.299 * (r11 - 128) + 0.587 * (g11 - 128) + 0.114 * (b11 - 128) + 128); /* u v */ uint8_t u1 = CLIP(((- 0.147 * (r00 - 128) - 0.289 * (g00 - 128) + 0.436 * (b00 - 128) + 128) + (- 0.147 * (r01 - 128) - 0.289 * (g01 - 128) + 0.436 * (b01 - 128) + 128))/2); uint8_t v1 =CLIP(((0.615 * (r00 - 128) - 0.515 * (g00 - 128) - 0.100 * (b00 - 128) + 128) + (0.615 * (r01 - 128) - 0.515 * (g01 - 128) - 0.100 * (b01 - 128) + 128))/2); uint8_t u2 = CLIP(((- 0.147 * (r10 - 128) - 0.289 * (g10 - 128) + 0.436 * (b10 - 128) + 128) + (- 0.147 * (r11 - 128) - 0.289 * (g11 - 128) + 0.436 * (b11 - 128) + 128))/2); uint8_t v2 =CLIP(((0.615 * (r10 - 128) - 0.515 * (g10 - 128) - 0.100 * (b10 - 128) + 128) + (0.615 * (r11 - 128) - 0.515 * (g11 - 128) - 0.100 * (b11 - 128) + 128))/2); *pu++ = (u1 + u2) / 2; *pv++ = (v1 + v2) / 2; } in1 = in2; py1 = py2; } } /* * convert ba24 to yu12 * args: * out: pointer to output buffer containing yu12 data * in: pointer to input buffer containing ba24 (rgb32) data * width: picture width * height: picture height * * asserts: * out is not null * in is not null * * returns: none */ void ba24_to_yu12(uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(out); assert(in); uint8_t *py1 = out;//first line uint8_t *py2 = py1 + width;//second line uint8_t *pu = out + (width * height); uint8_t *pv = pu + ((width * height) / 4); uint8_t *in1 = in; //first line uint8_t *in2 = in + (width * 4); //second line (4 byte per pixel) int h = 0; int w = 0; for(h = 0; h < height; h += 2) { in2 = in1 + (width * 4); py2 = py1 + width; for(w = 0; w < (width * 4); w +=8) { in1++; //first byte has alpha data uint8_t r00 = *in1++; uint8_t g00 = *in1++; uint8_t b00 = *in1++; /* y */ *py1++ = CLIP(0.299 * (r00 - 128) + 0.587 * (g00 - 128) + 0.114 * (b00 - 128) + 128); in1++; //first byte has alpha data uint8_t r01 = *in1++; uint8_t g01 = *in1++; uint8_t b01 = *in1++; /* y */ *py1++ = CLIP(0.299 * (r01 - 128) + 0.587 * (g01 - 128) + 0.114 * (b01 - 128) + 128); in2++; //first byte has alpha data uint8_t r10 = *in2++; uint8_t g10 = *in2++; uint8_t b10 = *in2++; /* y */ *py2++ = CLIP(0.299 * (r10 - 128) + 0.587 * (g10 - 128) + 0.114 * (b10 - 128) + 128); in2++; //first byte has alpha data uint8_t r11 = *in2++; uint8_t g11 = *in2++; uint8_t b11 = *in2++; /* y */ *py2++ = CLIP(0.299 * (r11 - 128) + 0.587 * (g11 - 128) + 0.114 * (b11 - 128) + 128); /* u v */ uint8_t u1 = CLIP(((- 0.147 * (r00 - 128) - 0.289 * (g00 - 128) + 0.436 * (b00 - 128) + 128) + (- 0.147 * (r01 - 128) - 0.289 * (g01 - 128) + 0.436 * (b01 - 128) + 128))/2); uint8_t v1 =CLIP(((0.615 * (r00 - 128) - 0.515 * (g00 - 128) - 0.100 * (b00 - 128) + 128) + (0.615 * (r01 - 128) - 0.515 * (g01 - 128) - 0.100 * (b01 - 128) + 128))/2); uint8_t u2 = CLIP(((- 0.147 * (r10 - 128) - 0.289 * (g10 - 128) + 0.436 * (b10 - 128) + 128) + (- 0.147 * (r11 - 128) - 0.289 * (g11 - 128) + 0.436 * (b11 - 128) + 128))/2); uint8_t v2 =CLIP(((0.615 * (r10 - 128) - 0.515 * (g10 - 128) - 0.100 * (b10 - 128) + 128) + (0.615 * (r11 - 128) - 0.515 * (g11 - 128) - 0.100 * (b11 - 128) + 128))/2); *pu++ = (u1 + u2) / 2; *pv++ = (v1 + v2) / 2; } in1 = in2; py1 = py2; } } /* * yu12 to rgb24 * args: * out - pointer to output rgb data buffer * in - pointer to input yu12 data buffer * width - buffer width (in pixels) * height - buffer height (in pixels) * * asserts: * none * * returns: none */ void yu12_to_rgb24 (uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(out); assert(in); uint8_t *py1 = in; //line 1 uint8_t *py2 = py1 + width; //line 2 uint8_t *pu = in + (width * height); uint8_t *pv = pu + ((width * height) / 4); uint8_t *pout1 = out; //first line uint8_t *pout2 = out + (width * 3); //second line int h=0, w=0; for(h=0; h < height; h+=2) //every two lines { py1 = in + (h * width); py2 = py1 + width; pout1 = out + (h * width * 3); pout2 = pout1 + (width * 3); for(w=0; w<width; w+=2) //every 2 pixels { /* standart: r = y0 + 1.402 (v-128) */ /* logitech: r = y0 + 1.370705 (v-128) */ *pout1++=CLIP(*py1 + 1.402 * (*pv-128)); *pout2++=CLIP(*py2 + 1.402 * (*pv-128)); /* standart: g = y0 - 0.34414 (u-128) - 0.71414 (v-128)*/ /* logitech: g = y0 - 0.337633 (u-128)- 0.698001 (v-128)*/ *pout1++=CLIP(*py1 - 0.34414 * (*pu-128) -0.71414*(*pv-128)); *pout2++=CLIP(*py2 - 0.34414 * (*pu-128) -0.71414*(*pv-128)); /* standart: b = y0 + 1.772 (u-128) */ /* logitech: b = y0 + 1.732446 (u-128) */ *pout1++=CLIP(*py1 + 1.772 *( *pu-128)); *pout2++=CLIP(*py2 + 1.772 *( *pu-128)); py1++; py2++; /* standart: r1 =y1 + 1.402 (v-128) */ /* logitech: r1 = y1 + 1.370705 (v-128) */ *pout1++=CLIP(*py1 + 1.402 * (*pv-128)); *pout2++=CLIP(*py2 + 1.402 * (*pv-128)); /* standart: g1 = y1 - 0.34414 (u-128) - 0.71414 (v-128)*/ /* logitech: g1 = y1 - 0.337633 (u-128)- 0.698001 (v-128)*/ *pout1++=CLIP(*py1 - 0.34414 * (*pu-128) -0.71414 * (*pv-128)); *pout2++=CLIP(*py2 - 0.34414 * (*pu-128) -0.71414 * (*pv-128)); /* standart: b1 = y1 + 1.772 (u-128) */ /* logitech: b1 = y1 + 1.732446 (u-128) */ *pout1++=CLIP(*py1 + 1.772 * (*pu-128)); *pout2++=CLIP(*py2 + 1.772 * (*pu-128)); py1++; py2++; pu++; pv++; } } } static __int64_t T1_402[256], T0_34414[256], T0_71414[256], T1_772[256]; void init_yuv2rgb_num_table() { for (int i = 0; i < 256; i++) { T1_402[i] = i * 5743; T1_402[i] = T1_402[i] >> 12; T0_34414[i] = i * 721714; T0_34414[i] = T0_34414[i] >> 21; T0_71414[i] = i * 5990641; T0_71414[i] = T0_71414[i] >> 23; T1_772[i] = i * 1858077; T1_772[i] = T1_772[i] >> 20; } } /* * yu12 to rgb24 high efficiency, use table inquer improve excution efficency * args: * out - pointer to output rgb data buffer * in - pointer to input yu12 data buffer * width - buffer width (in pixels) * height - buffer height (in pixels) * * asserts: * none * * returns: none */ #define F_H void yu12_to_rgb24_higheffic (uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(out); assert(in); uint8_t *py1 = in; //line 1 uint8_t *py2 = py1 + width; //line 2 uint8_t *pu = in + (width * height); uint8_t *pv = pu + ((width * height) / 4); uint8_t *pout1 = out; //first line uint8_t *pout2 = out + (width * 3); //second line int h=0, w=0; int groupSize = width * 3; int64_t v1_402, u0_34414_v0_71414, u1_772; for(h=0; h < height; h+=2) //every two lines { py1 = in + (h * width); py2 = py1 + width; pout1 = out + (h * groupSize); pout2 = pout1 + (groupSize); for(w=0; w<width; w+=2) //every 2 pixels { v1_402 = T1_402[*pv] - T1_402[128]; u0_34414_v0_71414 = T0_34414[*pu] - T0_34414[128] + T0_71414[*pv] - T0_71414[128]; u1_772 = T1_772[*pu] - T1_772[128]; // printf("v1_402i:%ld, uvi:%ld, u1_772i:%ld\n", v1_402, u0_34414_v0_71414, u1_772); // v1_402f = 1.402 * (*pv - 128); // u0_34414_v0_71414f = 0.34414 * (*pu - 128) + 0.71414 * (*pv - 128); // u1_772f = 1.772 * (*pu - 128); // printf("v1_402f:%f, uvf:%f, u1_772f:%f\n", v1_402f, u0_34414_v0_71414f, u1_772f); #ifdef F_H *pout1++=CLIP(*py1 + v1_402); *pout2++=CLIP(*py2 + v1_402); *pout1++=CLIP(*py1 - u0_34414_v0_71414); *pout2++=CLIP(*py2 - u0_34414_v0_71414); *pout1++=CLIP(*py1 + u1_772); *pout2++=CLIP(*py2 + u1_772); py1++; py2++; *pout1++=CLIP(*py1 + v1_402); *pout2++=CLIP(*py2 + v1_402); *pout1++=CLIP(*py1 - u0_34414_v0_71414); *pout2++=CLIP(*py2 - u0_34414_v0_71414); *pout1++=CLIP(*py1 + u1_772); *pout2++=CLIP(*py2 + u1_772); #elif defined F_L // uint8_t t1 = CLIP(v1_402f); // uint8_t t2 = CLIP(u0_34414_v0_71414f); // uint8_t t3 = CLIP(u1_772f); // printf("v1_402_ui:%d, uv_ui:%d, u1_772_ui:%d\n", t1, t2, t3); v1_402f = 1.402 * (*pv - 128); u0_34414_v0_71414f = 0.34414 * (*pu - 128) + 0.71414 * (*pv - 128); u1_772f = 1.722 * (*pu - 128); *pout1++=CLIP(*py1 + v1_402f); *pout2++=CLIP(*py2 + v1_402f); *pout1++=CLIP(*py1 - u0_34414_v0_71414f); *pout2++=CLIP(*py2 - u0_34414_v0_71414f); *pout1++=CLIP(*py1 + u1_772f); *pout2++=CLIP(*py2 + u1_772f); py1++; py2++; *pout1++=CLIP(*py1 + v1_402f); *pout2++=CLIP(*py2 + v1_402f); *pout1++=CLIP(*py1 - u0_34414_v0_71414f); *pout2++=CLIP(*py2 - u0_34414_v0_71414f); *pout1++=CLIP(*py1 + u1_772f); *pout2++=CLIP(*py2 + u1_772f); #else *pout1++=CLIP(*py1 + 1.402 * (*pv-128)); *pout2++=CLIP(*py2 + 1.402 * (*pv-128)); *pout1++=CLIP(*py1 - 0.34414 * (*pu-128) -0.71414*(*pv-128)); *pout2++=CLIP(*py2 - 0.34414 * (*pu-128) -0.71414*(*pv-128)); *pout1++=CLIP(*py1 + 1.772 *( *pu-128)); *pout2++=CLIP(*py2 + 1.772 *( *pu-128)); py1++; py2++; *pout1++=CLIP(*py1 + 1.402 * (*pv-128)); *pout2++=CLIP(*py2 + 1.402 * (*pv-128)); *pout1++=CLIP(*py1 - 0.34414 * (*pu-128) -0.71414 * (*pv-128)); *pout2++=CLIP(*py2 - 0.34414 * (*pu-128) -0.71414 * (*pv-128)); *pout1++=CLIP(*py1 + 1.772 * (*pu-128)); *pout2++=CLIP(*py2 + 1.772 * (*pu-128)); #endif py1++; py2++; pu++; pv++; } } } /* * FIXME: yu12 to bgr24 with lines upsidedown * used for bitmap files (DIB24) * args: * out - pointer to output bgr data buffer * in - pointer to input yu12 data buffer * width - buffer width (in pixels) * height - buffer height (in pixels) * * asserts: * none * * returns: none */ void yu12_to_dib24 (uint8_t *out, uint8_t *in, int width, int height) { /*assertions*/ assert(out); assert(in); uint8_t *py1 = in + (height * width) - width; //begin of last line uint8_t *py2 = py1 - width; //last line -1 uint8_t *pu = in + ((width * height * 5) / 4) - (width/2); //begin of last line uint8_t *pv = pu + ((width * height) / 4); //begin of last line uint8_t *pout1 = out; //first line uint8_t *pout2 = pout1 + (width * 3); //second line int h=0, w=0; int uvline = height/2; for(h=height; h >0 ; h-=2) //every two lines { uvline--; //begin of uv line py1 = in + ((h-1) * width); py2 = py1 - width; pu = in + (width * height) + ((uvline * width)/2); pv = pu + ((width * height) / 4); pout1 = out + ((height-h) * width * 3); pout2 = pout1 + (width * 3); for(w=0; w<width; w+=2) //every 2 pixels { /* standart: b = y0 + 1.772 (u-128) */ /* logitech: b = y0 + 1.732446 (u-128) */ *pout1++=CLIP(*py1 + 1.772 *( *pu-128)); *pout2++=CLIP(*py2 + 1.772 *( *pu-128)); /* standart: g = y0 - 0.34414 (u-128) - 0.71414 (v-128)*/ /* logitech: g = y0 - 0.337633 (u-128)- 0.698001 (v-128)*/ *pout1++=CLIP(*py1 - 0.34414 * (*pu-128) -0.71414*(*pv-128)); *pout2++=CLIP(*py2 - 0.34414 * (*pu-128) -0.71414*(*pv-128)); /* standart: r = y0 + 1.402 (v-128) */ /* logitech: r = y0 + 1.370705 (v-128) */ *pout1++=CLIP(*py1 + 1.402 * (*pv-128)); *pout2++=CLIP(*py2 + 1.402 * (*pv-128)); py1++; py2++; /* standart: b = y0 + 1.772 (u-128) */ /* logitech: b = y0 + 1.732446 (u-128) */ *pout1++=CLIP(*py1 + 1.772 *( *pu-128)); *pout2++=CLIP(*py2 + 1.772 *( *pu-128)); /* standart: g = y0 - 0.34414 (u-128) - 0.71414 (v-128)*/ /* logitech: g = y0 - 0.337633 (u-128)- 0.698001 (v-128)*/ *pout1++=CLIP(*py1 - 0.34414 * (*pu-128) -0.71414*(*pv-128)); *pout2++=CLIP(*py2 - 0.34414 * (*pu-128) -0.71414*(*pv-128)); /* standart: r = y0 + 1.402 (v-128) */ /* logitech: r = y0 + 1.370705 (v-128) */ *pout1++=CLIP(*py1 + 1.402 * (*pv-128)); *pout2++=CLIP(*py2 + 1.402 * (*pv-128)); py1++; py2++; pu++; pv++; } } } /* * convert yuv 420 planar (yu12) to yuv 422 (save_image_jpeg) * args: * out- pointer to output buffer (yuyv) * in- pointer to input buffer (yuv420 planar data frame (yu12)) * width- picture width * height- picture height * * asserts: * out is not null * in is not null * * returns: none */ void yu12_to_yuyv (uint8_t *out, uint8_t *in, int width, int height) { uint8_t *py; uint8_t *pu; uint8_t *pv; int linesize = width * 2; int uvlinesize = width / 2; py=in; pu=py+(width*height); pv=pu+(width*height/4); int h=0; int huv=0; for(h=0;h<height;h+=2) { int wy = 0; int wuv = 0; int offset = h * linesize; int offset1 = (h + 1) * linesize; int offsety = h * width; int offsety1 = (h + 1) * width; int offsetuv = huv * uvlinesize; int w = 0; for(w=0;w<linesize;w+=4) { /*y00*/ out[w + offset] = py[wy + offsety]; /*u0*/ out[(w + 1) + offset] = pu[wuv + offsetuv]; /*y01*/ out[(w + 2) + offset] = py[(wy + 1) + offsety]; /*v0*/ out[(w + 3) + offset] = pv[wuv + offsetuv]; /*y10*/ out[w + offset1] = py[wy + offsety1]; /*u0*/ out[(w + 1) + offset1] = pu[wuv + offsetuv]; /*y11*/ out[(w + 2) + offset1] = py[(wy + 1) + offsety1]; /*v0*/ out[(w + 3) + offset1] = pv[wuv + offsetuv]; wuv++; wy+=2; } huv++; } } #if MJPG_BUILTIN //use internal jpeg decoder /* * used for internal jpeg decoding 420 planar to 422 * args: * out: pointer to data output of idct (macroblocks yyyy u v) * pic: pointer to picture buffer (yuyv) * width: picture width * * asserts: * none * * returns: none */ void yuv420pto422(int *out, uint8_t *pic, int width) { int j = 0; int outy1 = 0; int outy2 = 8; //yyyyuv uint8_t *pic0 = pic; uint8_t *pic1 = pic + width; int *outy = out; int *outu = out + 64 * 4; int *outv = out + 64 * 5; for (j = 0; j < 8; j++) { int k = 0; for (k = 0; k < 8; k++) { if( k == 4) { outy1 += 56; outy2 += 56; } *pic0++ = CLIP(outy[outy1]); //y1 line 1 *pic0++ = CLIP(128 + *outu); //u line 1-2 *pic0++ = CLIP(outy[outy1+1]); //y2 line 1 *pic0++ = CLIP(128 + *outv); //v line 1-2 *pic1++ = CLIP(outy[outy2]); //y1 line 2 *pic1++ = CLIP(128 + *outu); //u line 1-2 *pic1++ = CLIP(outy[outy2+1]); //y2 line 2 *pic1++ = CLIP(128 + *outv); //v line 1-2 outy1 +=2; outy2 += 2; outu++; outv++; } if(j==3) { outy = out + 128; } else { outy += 16; } outy1 = 0; outy2 = 8; pic0 += 2 * (width -16); pic1 += 2 * (width -16); } } /* * used for internal jpeg decoding 422 planar to 422 * args: * out: pointer to data output of idct (macroblocks yyyy u v) * pic: pointer to picture buffer (yuyv) * width: picture width * * asserts: * none * * returns: none */ void yuv422pto422(int *out, uint8_t *pic, int width) { int j = 0; int outy1 = 0; int outy2 = 8; int outu1 = 0; int outv1 = 0; //yyyyuv uint8_t *pic0 = pic; uint8_t *pic1 = pic + width; int *outy = out; int *outu = out + 64 * 4; int *outv = out + 64 * 5; for (j = 0; j < 4; j++) { int k = 0; for (k = 0; k < 8; k++) { if( k == 4) { outy1 += 56; outy2 += 56; } *pic0++ = CLIP(outy[outy1]); //y1 line 1 *pic0++ = CLIP(128 + outu[outu1]); //u line 1 *pic0++ = CLIP(outy[outy1+1]); //y2 line 1 *pic0++ = CLIP(128 + outv[outv1]); //v line 1 *pic1++ = CLIP(outy[outy2]); //y1 line 2 *pic1++ = CLIP(128 + outu[outu1+8]);//u line 2 *pic1++ = CLIP(outy[outy2+1]); //y2 line 2 *pic1++ = CLIP(128 + outv[outv1+8]);//v line 2 outv1 += 1; outu1 += 1; outy1 +=2; outy2 +=2; } outy += 16;outu +=8; outv +=8; outv1 = 0; outu1=0; outy1 = 0; outy2 = 8; pic0 += 2 * (width -16); pic1 += 2 * (width -16); } } /* * used for internal jpeg decoding 444 planar to 422 * args: * out: pointer to data output of idct (macroblocks yyyy u v) * pic: pointer to picture buffer (yuyv) * width: picture width * * asserts: * none * * returns: none */ void yuv444pto422(int *out, uint8_t *pic, int width) { int j = 0; int outy1 = 0; int outy2 = 8; int outu1 = 0; int outv1 = 0; //yyyyuv uint8_t *pic0 = pic; uint8_t *pic1 = pic + width; int *outy = out; int *outu = out + 64 * 4; // Ooops where did i invert ?? int *outv = out + 64 * 5; for (j = 0; j < 4; j++) { int k = 0; for (k = 0; k < 4; k++) { *pic0++ =CLIP( outy[outy1]); //y1 line 1 *pic0++ =CLIP( 128 + outu[outu1]); //u line 1 *pic0++ =CLIP( outy[outy1+1]); //y2 line 1 *pic0++ =CLIP( 128 + outv[outv1]); //v line 1 *pic1++ =CLIP( outy[outy2]); //y1 line 2 *pic1++ =CLIP( 128 + outu[outu1+8]);//u line 2 *pic1++ =CLIP( outy[outy2+1]); //y2 line 2 *pic1++ =CLIP( 128 + outv[outv1+8]);//v line 2 outv1 += 2; outu1 += 2; outy1 +=2; outy2 +=2; } outy += 16;outu +=16; outv +=16; outv1 = 0; outu1=0; outy1 = 0; outy2 = 8; pic0 += 2 * (width -8); pic1 += 2 * (width -8); } } /* * used for internal jpeg decoding 400 planar to 422 * args: * out: pointer to data output of idct (macroblocks yyyy ) * pic: pointer to picture buffer (yuyv) * width: picture width * * asserts: * none * * returns: none */ void yuv400pto422(int *out, uint8_t *pic, int width) { int j = 0; int outy1 = 0; int outy2 = 8; uint8_t *pic0 = pic; uint8_t *pic1 = pic + width; int *outy = out; //yyyy for (j = 0; j < 4; j++) { int k = 0; for (k = 0; k < 4; k++) { *pic0++ = CLIP(outy[outy1]); //y1 line 1 *pic0++ = 128 ; //u *pic0++ = CLIP(outy[outy1+1]);//y2 line 1 *pic0++ = 128 ; //v *pic1++ = CLIP(outy[outy2]); //y1 line 2 *pic1++ = 128 ; //u *pic1++ = CLIP(outy[outy2+1]);//y2 line 2 *pic1++ = 128 ; //v outy1 +=2; outy2 +=2; } outy += 16; outy1 = 0; outy2 = 8; pic0 += 2 * (width -8); pic1 += 2 * (width -8); } } #endif
83,244
C
.c
2,883
25.638224
110
0.527696
linuxdeepin/dtkmultimedia
3
16
2
LGPL-3.0
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
15,285,559
save_image.c
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam_v4l2core/save_image.c
/*******************************************************************************# # guvcview http://guvcview.sourceforge.net # # # # Paulo Assis <[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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # ********************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <inttypes.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <errno.h> #include <assert.h> #include "gviewv4l2core.h" #include "save_image.h" #include "colorspaces.h" extern int verbosity; /* * save data to file * args: * filename - string with filename * data - pointer to data * size - data size in bytes = sizeof(uint8_t) * * asserts: * none * * returns: error code */ int v4l2core_save_data_to_file(const char *filename, uint8_t *data, int size) { FILE *fp; int ret = 0; if ((fp = fopen(filename, "wb")) !=NULL) { ret = fwrite(data, size, 1, fp); if (ret<1) ret=1;/*write error*/ else ret=0; fflush(fp); /*flush data stream to file system*/ if(fsync(fileno(fp)) || fclose(fp)) fprintf(stderr, "V4L2_CORE: (save_data_to_file) error - couldn't write buffer to file: %s\n", strerror(errno)); else if(verbosity > 0) printf("V4L2_CORE: saved data to %s\n", filename); } else ret = 1; return (ret); } /* * save the current frame to file * args: * frame - pointer to frame buffer * filename - output file name * format - image type * (IMG_FMT_RAW, IMG_FMT_JPG, IMG_FMT_PNG, IMG_FMT_BMP) * * asserts: * none * * returns: error code */ int save_frame_image(v4l2_frame_buff_t *frame, const char *filename, int format) { int ret= E_OK; switch(format) { case IMG_FMT_RAW: if(verbosity > 0) printf("V4L2_CORE: saving raw data to %s\n", filename); ret = v4l2core_save_data_to_file(filename, frame->raw_frame, frame->raw_frame_size); break; case IMG_FMT_JPG: if(verbosity > 0) printf("V4L2_CORE: saving jpeg frame to %s\n", filename); ret = save_image_jpeg(frame, filename); break; case IMG_FMT_BMP: if(verbosity > 0) printf("V4L2_CORE: saving bmp frame to %s\n", filename); ret = save_image_bmp(frame, filename); break; // case IMG_FMT_PNG: // if(verbosity > 0) // printf("V4L2_CORE: saving png frame to %s\n", filename); // ret = save_image_png(frame, filename); // break; default: fprintf(stderr, "V4L2_CORE: (save_image) Image format %i not supported\n", format); ret = E_FORMAT_ERR; break; } return ret; }
3,900
C
.c
108
33.916667
114
0.536263
linuxdeepin/dtkmultimedia
3
16
2
LGPL-3.0
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
15,285,565
cameraconfig.h
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam/cameraconfig.h
/*******************************************************************************# # guvcview http://guvcview.sourceforge.net # # # # Paulo Assis <[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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # ********************************************************************************/ #ifndef CONFIG_H #define CONFIG_H #include <stdint.h> #include <stdio.h> #include "camoptions.h" #define PACKAGE_LOCALE_DIR "./" #define GETTEXT_PACKAGE "cheese" //#define VERSION "cheese-1.0" #define HAS_QT5 1 #define ENABLE_SDL2 1 #ifndef GETTEXT_PACKAGE_V4L2CORE # define GETTEXT_PACKAGE_V4L2CORE "gview_v4l2core" #endif typedef struct _config_t { int width; /*width*/ int height; /*height*/ char *device_name; /*device name*/ char *device_location; /*device location*/ unsigned int format; /*pixelformat - v4l2 fourcc*/ char render[5]; /*render api*/ char gui[5]; /*gui api*/ char audio[6]; /*audio api - none; port; pulse*/ char capture[5]; /*capture method: read or mmap*/ char video_codec[5]; /*video codec*/ char audio_codec[5]; /*video codec*/ char *profile_path; char *profile_name; char *video_path; char *video_name; char *photo_path; char *photo_name; int video_sufix; /*flag if video file has auto suffix enable*/ int photo_sufix; /*flag if photo file has auto suffix enable*/ int fps_num; int fps_denom; int audio_device; /*audio device index*/ uint32_t video_fx; uint32_t audio_fx; uint32_t osd_mask; /*OSD bit mask*/ uint32_t crosshair_color; /*osd crosshair rgb color (0x00RRGGBB)*/ } config_t; /*video sufix flag*/ __attribute__((unused)) static int video_sufix_flag = 1; /*photo sufix flag*/ __attribute__((unused)) static int photo_sufix_flag = 1; /*control profile file name*/ __attribute__((unused)) static char *profile_name = NULL; /*divece name*/ __attribute__((unused)) static char *device_name = NULL; /*device location*/ __attribute__((unused)) static char *device_location = NULL; /*control profile path to dir*/ __attribute__((unused)) static char *profile_path = NULL; __attribute__((unused)) static int debug_level; /* * get the internal config data * args: * none * * asserts: * none * * returns: pointer to internal config_t struct */ config_t *config_get(); /* * sets the photo sufix flag * args: * flag: photo sufix flag * * asserts: * none * * returns: none */ void set_photo_sufix_flag(int flag); /* * sets the device location * args: * name: device location * * asserts: * none * * returns: none */ void set_device_location(const char *name); /* * sets the device name * args: * name: device name * * asserts: * none * * returns: none */ void set_device_name(const char *name); /* * sets the control profile file name * args: * name: control profile file name * * asserts: * none * * returns: none */ void set_profile_name(const char *name); /* * sets the control profile path (to dir) * args: * path: control profile path * * asserts: * none * * returns: none */ void set_profile_path(const char *path); /* * gets the control profile path (to dir) * args: * none * * asserts: * none * * returns: control profile file name */ /* * save options to config file * args: * filename - config file * * asserts: * none * * returns: error code */ int config_save(const char *filename); /* * load options from config file * args: * filename - config file * * asserts: * none * * returns: error code */ int config_load(const char *filename); /* * update config data with options data * args: * my_options - pointer to options data * * asserts: * none * * returns: none */ void config_update(options_t *my_options); /* * sets the video sufix flag * args: * flag: video sufix flag * * asserts: * none * * returns: none */ void set_video_sufix_flag(int flag); /* * cleans internal config allocations * args: * none * * asserts: * none * * returns: none */ void config_clean(); #endif
5,448
C
.c
207
24.169082
81
0.577756
linuxdeepin/dtkmultimedia
3
16
2
LGPL-3.0
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false