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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2,495 |
vaapi-utils.c
|
obsproject_obs-studio/plugins/obs-ffmpeg/vaapi-utils.c
|
// SPDX-FileCopyrightText: 2022 tytan652 <[email protected]>
//
// SPDX-License-Identifier: GPL-2.0-or-later
#include "vaapi-utils.h"
#include <util/bmem.h>
#include <util/dstr.h>
#include <va/va_drm.h>
#include <va/va_str.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
static bool version_logged = false;
inline static VADisplay vaapi_open_display_drm(int *fd, const char *device_path)
{
VADisplay va_dpy;
if (!device_path)
return NULL;
*fd = open(device_path, O_RDWR);
if (*fd < 0) {
blog(LOG_ERROR, "VAAPI: Failed to open device '%s'", device_path);
return NULL;
}
va_dpy = vaGetDisplayDRM(*fd);
if (!va_dpy) {
blog(LOG_ERROR, "VAAPI: Failed to initialize DRM display");
return NULL;
}
return va_dpy;
}
inline static void vaapi_close_display_drm(int *fd)
{
if (*fd < 0)
return;
close(*fd);
*fd = -1;
}
static void vaapi_log_info_cb(void *user_context, const char *message)
{
UNUSED_PARAMETER(user_context);
// Libva message always ends with a newline
struct dstr m;
dstr_init_copy(&m, message);
dstr_depad(&m);
blog(LOG_DEBUG, "Libva: %s", m.array);
dstr_free(&m);
}
static void vaapi_log_error_cb(void *user_context, const char *message)
{
UNUSED_PARAMETER(user_context);
// Libva message always ends with a newline
struct dstr m;
dstr_init_copy(&m, message);
dstr_depad(&m);
blog(LOG_DEBUG, "Libva error: %s", m.array);
dstr_free(&m);
}
VADisplay vaapi_open_device(int *fd, const char *device_path, const char *func_name)
{
VADisplay va_dpy;
VAStatus va_status;
int major, minor;
const char *driver;
va_dpy = vaapi_open_display_drm(fd, device_path);
if (!va_dpy)
return NULL;
blog(LOG_DEBUG, "VAAPI: Initializing display in %s", func_name);
vaSetInfoCallback(va_dpy, vaapi_log_info_cb, NULL);
vaSetErrorCallback(va_dpy, vaapi_log_error_cb, NULL);
va_status = vaInitialize(va_dpy, &major, &minor);
if (va_status != VA_STATUS_SUCCESS) {
blog(LOG_ERROR, "VAAPI: Failed to initialize display in %s", func_name);
vaapi_close_device(fd, va_dpy);
return NULL;
}
blog(LOG_DEBUG, "VAAPI: Display initialized");
if (!version_logged) {
blog(LOG_INFO, "VAAPI: API version %d.%d", major, minor);
version_logged = true;
}
driver = vaQueryVendorString(va_dpy);
blog(LOG_DEBUG, "VAAPI: '%s' in use for device '%s'", driver, device_path);
return va_dpy;
}
void vaapi_close_device(int *fd, VADisplay dpy)
{
vaTerminate(dpy);
vaapi_close_display_drm(fd);
}
static uint32_t vaapi_display_ep_combo_rate_controls(VAProfile profile, VAEntrypoint entrypoint, VADisplay dpy,
const char *device_path)
{
VAStatus va_status;
VAConfigAttrib attrib[1];
attrib->type = VAConfigAttribRateControl;
va_status = vaGetConfigAttributes(dpy, profile, entrypoint, attrib, 1);
switch (va_status) {
case VA_STATUS_SUCCESS:
return attrib->value;
case VA_STATUS_ERROR_UNSUPPORTED_PROFILE:
blog(LOG_DEBUG, "VAAPI: %s is not supported by the device '%s'", vaProfileStr(profile), device_path);
return 0;
case VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT:
blog(LOG_DEBUG, "VAAPI: %s %s is not supported by the device '%s'", vaProfileStr(profile),
vaEntrypointStr(entrypoint), device_path);
return 0;
default:
blog(LOG_ERROR, "VAAPI: Fail to get RC attribute from the %s %s of the device '%s'",
vaProfileStr(profile), vaEntrypointStr(entrypoint), device_path);
return 0;
}
}
static bool vaapi_display_ep_combo_supported(VAProfile profile, VAEntrypoint entrypoint, VADisplay dpy,
const char *device_path)
{
uint32_t ret = vaapi_display_ep_combo_rate_controls(profile, entrypoint, dpy, device_path);
if (ret & VA_RC_CBR || ret & VA_RC_CQP || ret & VA_RC_VBR)
return true;
return false;
}
bool vaapi_device_rc_supported(VAProfile profile, VADisplay dpy, uint32_t rc, const char *device_path)
{
uint32_t ret = vaapi_display_ep_combo_rate_controls(profile, VAEntrypointEncSlice, dpy, device_path);
if (ret & rc)
return true;
ret = vaapi_display_ep_combo_rate_controls(profile, VAEntrypointEncSliceLP, dpy, device_path);
if (ret & rc)
return true;
return false;
}
static bool vaapi_display_ep_bframe_supported(VAProfile profile, VAEntrypoint entrypoint, VADisplay dpy)
{
VAStatus va_status;
VAConfigAttrib attrib[1];
attrib->type = VAConfigAttribEncMaxRefFrames;
va_status = vaGetConfigAttributes(dpy, profile, entrypoint, attrib, 1);
if (va_status == VA_STATUS_SUCCESS && attrib->value != VA_ATTRIB_NOT_SUPPORTED)
return attrib->value >> 16;
return false;
}
bool vaapi_device_bframe_supported(VAProfile profile, VADisplay dpy)
{
bool ret = vaapi_display_ep_bframe_supported(profile, VAEntrypointEncSlice, dpy);
if (ret)
return true;
ret = vaapi_display_ep_bframe_supported(profile, VAEntrypointEncSliceLP, dpy);
if (ret)
return true;
return false;
}
#define CHECK_PROFILE(ret, profile, va_dpy, device_path) \
if (vaapi_display_ep_combo_supported(profile, VAEntrypointEncSlice, va_dpy, device_path)) { \
blog(LOG_DEBUG, "'%s' support encoding with %s", device_path, vaProfileStr(profile)); \
ret |= true; \
}
#define CHECK_PROFILE_LP(ret, profile, va_dpy, device_path) \
if (vaapi_display_ep_combo_supported(profile, VAEntrypointEncSliceLP, va_dpy, device_path)) { \
blog(LOG_DEBUG, "'%s' support low power encoding with %s", device_path, vaProfileStr(profile)); \
ret |= true; \
}
bool vaapi_display_h264_supported(VADisplay dpy, const char *device_path)
{
bool ret = false;
CHECK_PROFILE(ret, VAProfileH264ConstrainedBaseline, dpy, device_path);
CHECK_PROFILE(ret, VAProfileH264Main, dpy, device_path);
CHECK_PROFILE(ret, VAProfileH264High, dpy, device_path);
if (!ret) {
CHECK_PROFILE_LP(ret, VAProfileH264ConstrainedBaseline, dpy, device_path);
CHECK_PROFILE_LP(ret, VAProfileH264Main, dpy, device_path);
CHECK_PROFILE_LP(ret, VAProfileH264High, dpy, device_path);
}
return ret;
}
bool vaapi_device_h264_supported(const char *device_path)
{
bool ret = false;
VADisplay va_dpy;
int drm_fd = -1;
va_dpy = vaapi_open_device(&drm_fd, device_path, "vaapi_device_h264_supported");
if (!va_dpy)
return false;
ret = vaapi_display_h264_supported(va_dpy, device_path);
vaapi_close_device(&drm_fd, va_dpy);
return ret;
}
const char *vaapi_get_h264_default_device()
{
static const char *default_h264_device = NULL;
if (!default_h264_device) {
bool ret = false;
char path[32] = "/dev/dri/renderD1";
for (int i = 28;; i++) {
sprintf(path, "/dev/dri/renderD1%d", i);
if (access(path, F_OK) != 0)
break;
ret = vaapi_device_h264_supported(path);
if (ret) {
default_h264_device = strdup(path);
break;
}
}
}
return default_h264_device;
}
bool vaapi_display_av1_supported(VADisplay dpy, const char *device_path)
{
bool ret = false;
CHECK_PROFILE(ret, VAProfileAV1Profile0, dpy, device_path);
if (!ret) {
CHECK_PROFILE_LP(ret, VAProfileAV1Profile0, dpy, device_path);
}
return ret;
}
bool vaapi_device_av1_supported(const char *device_path)
{
bool ret = false;
VADisplay va_dpy;
int drm_fd = -1;
va_dpy = vaapi_open_device(&drm_fd, device_path, "vaapi_device_av1_supported");
if (!va_dpy)
return false;
ret = vaapi_display_av1_supported(va_dpy, device_path);
vaapi_close_device(&drm_fd, va_dpy);
return ret;
}
const char *vaapi_get_av1_default_device()
{
static const char *default_av1_device = NULL;
if (!default_av1_device) {
bool ret = false;
char path[32] = "/dev/dri/renderD1";
for (int i = 28;; i++) {
sprintf(path, "/dev/dri/renderD1%d", i);
if (access(path, F_OK) != 0)
break;
ret = vaapi_device_av1_supported(path);
if (ret) {
default_av1_device = strdup(path);
break;
}
}
}
return default_av1_device;
}
#ifdef ENABLE_HEVC
bool vaapi_display_hevc_supported(VADisplay dpy, const char *device_path)
{
bool ret = false;
CHECK_PROFILE(ret, VAProfileHEVCMain, dpy, device_path);
CHECK_PROFILE(ret, VAProfileHEVCMain10, dpy, device_path);
if (!ret) {
CHECK_PROFILE_LP(ret, VAProfileHEVCMain, dpy, device_path);
CHECK_PROFILE_LP(ret, VAProfileHEVCMain10, dpy, device_path);
}
return ret;
}
bool vaapi_device_hevc_supported(const char *device_path)
{
bool ret = false;
VADisplay va_dpy;
int drm_fd = -1;
va_dpy = vaapi_open_device(&drm_fd, device_path, "vaapi_device_hevc_supported");
if (!va_dpy)
return false;
ret = vaapi_display_hevc_supported(va_dpy, device_path);
vaapi_close_device(&drm_fd, va_dpy);
return ret;
}
const char *vaapi_get_hevc_default_device()
{
static const char *default_hevc_device = NULL;
if (!default_hevc_device) {
bool ret = false;
char path[32] = "/dev/dri/renderD1";
for (int i = 28;; i++) {
sprintf(path, "/dev/dri/renderD1%d", i);
if (access(path, F_OK) != 0)
break;
ret = vaapi_device_hevc_supported(path);
if (ret) {
default_hevc_device = strdup(path);
break;
}
}
}
return default_hevc_device;
}
#endif // #ifdef ENABLE_HEVC
| 9,211 |
C
|
.c
| 287 | 29.557491 | 113 | 0.700861 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,496 |
obs-ffmpeg-video-encoders.c
|
obsproject_obs-studio/plugins/obs-ffmpeg/obs-ffmpeg-video-encoders.c
|
#include "obs-ffmpeg-video-encoders.h"
#define do_log(level, format, ...) \
blog(level, "[%s encoder: '%s'] " format, enc->enc_name, obs_encoder_get_name(enc->encoder), ##__VA_ARGS__)
#define error(format, ...) do_log(LOG_ERROR, format, ##__VA_ARGS__)
#define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
#define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
#define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
bool ffmpeg_video_encoder_init_codec(struct ffmpeg_video_encoder *enc)
{
int ret = avcodec_open2(enc->context, enc->avcodec, NULL);
if (ret < 0) {
if (!obs_encoder_get_last_error(enc->encoder)) {
if (enc->on_init_error) {
enc->on_init_error(enc->parent, ret);
} else {
struct dstr error_message = {0};
dstr_copy(&error_message, obs_module_text("Encoder.Error"));
dstr_replace(&error_message, "%1", enc->enc_name);
dstr_replace(&error_message, "%2", av_err2str(ret));
dstr_cat(&error_message, "<br><br>");
obs_encoder_set_last_error(enc->encoder, error_message.array);
dstr_free(&error_message);
}
}
return false;
}
enc->vframe = av_frame_alloc();
if (!enc->vframe) {
warn("Failed to allocate video frame");
return false;
}
enc->vframe->format = enc->context->pix_fmt;
enc->vframe->width = enc->context->width;
enc->vframe->height = enc->context->height;
enc->vframe->color_range = enc->context->color_range;
enc->vframe->color_primaries = enc->context->color_primaries;
enc->vframe->color_trc = enc->context->color_trc;
enc->vframe->colorspace = enc->context->colorspace;
enc->vframe->chroma_location = enc->context->chroma_sample_location;
ret = av_frame_get_buffer(enc->vframe, base_get_alignment());
if (ret < 0) {
warn("Failed to allocate vframe: %s", av_err2str(ret));
return false;
}
enc->initialized = true;
return true;
}
void ffmpeg_video_encoder_update(struct ffmpeg_video_encoder *enc, int bitrate, int keyint_sec,
const struct video_output_info *voi, const struct video_scale_info *info,
const char *ffmpeg_opts)
{
const int rate = bitrate * 1000;
const enum AVPixelFormat pix_fmt = obs_to_ffmpeg_video_format(info->format);
enc->context->bit_rate = rate;
enc->context->rc_buffer_size = rate;
enc->context->width = obs_encoder_get_width(enc->encoder);
enc->context->height = obs_encoder_get_height(enc->encoder);
enc->context->time_base = (AVRational){voi->fps_den, voi->fps_num};
enc->context->framerate = (AVRational){voi->fps_num, voi->fps_den};
enc->context->pix_fmt = pix_fmt;
enc->context->color_range = info->range == VIDEO_RANGE_FULL ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
enum AVColorSpace colorspace = AVCOL_SPC_UNSPECIFIED;
switch (info->colorspace) {
case VIDEO_CS_601:
enc->context->color_primaries = AVCOL_PRI_SMPTE170M;
enc->context->color_trc = AVCOL_TRC_SMPTE170M;
colorspace = AVCOL_SPC_SMPTE170M;
break;
case VIDEO_CS_DEFAULT:
case VIDEO_CS_709:
enc->context->color_primaries = AVCOL_PRI_BT709;
enc->context->color_trc = AVCOL_TRC_BT709;
colorspace = AVCOL_SPC_BT709;
break;
case VIDEO_CS_SRGB:
enc->context->color_primaries = AVCOL_PRI_BT709;
enc->context->color_trc = AVCOL_TRC_IEC61966_2_1;
colorspace = AVCOL_SPC_BT709;
break;
case VIDEO_CS_2100_PQ:
enc->context->color_primaries = AVCOL_PRI_BT2020;
enc->context->color_trc = AVCOL_TRC_SMPTE2084;
colorspace = AVCOL_SPC_BT2020_NCL;
break;
case VIDEO_CS_2100_HLG:
enc->context->color_primaries = AVCOL_PRI_BT2020;
enc->context->color_trc = AVCOL_TRC_ARIB_STD_B67;
colorspace = AVCOL_SPC_BT2020_NCL;
}
enc->context->colorspace = colorspace;
enc->context->chroma_sample_location = determine_chroma_location(pix_fmt, colorspace);
if (keyint_sec)
enc->context->gop_size = keyint_sec * voi->fps_num / voi->fps_den;
enc->height = enc->context->height;
struct obs_options opts = obs_parse_options(ffmpeg_opts);
for (size_t i = 0; i < opts.count; i++) {
struct obs_option *opt = &opts.options[i];
av_opt_set(enc->context->priv_data, opt->name, opt->value, 0);
}
obs_free_options(opts);
}
void ffmpeg_video_encoder_free(struct ffmpeg_video_encoder *enc)
{
if (enc->initialized) {
AVPacket pkt = {0};
int r_pkt = 1;
/* flush remaining data */
avcodec_send_frame(enc->context, NULL);
while (r_pkt) {
if (avcodec_receive_packet(enc->context, &pkt) < 0)
break;
if (r_pkt)
av_packet_unref(&pkt);
}
}
avcodec_free_context(&enc->context);
av_frame_unref(enc->vframe);
av_frame_free(&enc->vframe);
da_free(enc->buffer);
}
bool ffmpeg_video_encoder_init(struct ffmpeg_video_encoder *enc, void *parent, obs_encoder_t *encoder,
const char *enc_lib, const char *enc_lib2, const char *enc_name,
init_error_cb on_init_error, first_packet_cb on_first_packet)
{
enc->encoder = encoder;
enc->parent = parent;
enc->avcodec = avcodec_find_encoder_by_name(enc_lib);
if (!enc->avcodec && enc_lib2)
enc->avcodec = avcodec_find_encoder_by_name(enc_lib2);
enc->enc_name = enc_name;
enc->on_init_error = on_init_error;
enc->on_first_packet = on_first_packet;
enc->first_packet = true;
blog(LOG_INFO, "---------------------------------");
if (!enc->avcodec) {
struct dstr error_message;
dstr_printf(&error_message, "Couldn't find encoder: %s", enc_lib);
obs_encoder_set_last_error(encoder, error_message.array);
dstr_free(&error_message);
warn("Couldn't find encoder: '%s'", enc_lib);
return false;
}
enc->context = avcodec_alloc_context3(enc->avcodec);
if (!enc->context) {
warn("Failed to create codec context");
return false;
}
return true;
}
static inline void copy_data(AVFrame *pic, const struct encoder_frame *frame, int height, enum AVPixelFormat format)
{
int h_chroma_shift, v_chroma_shift;
av_pix_fmt_get_chroma_sub_sample(format, &h_chroma_shift, &v_chroma_shift);
for (int plane = 0; plane < MAX_AV_PLANES; plane++) {
if (!frame->data[plane])
continue;
int frame_rowsize = (int)frame->linesize[plane];
int pic_rowsize = pic->linesize[plane];
int bytes = frame_rowsize < pic_rowsize ? frame_rowsize : pic_rowsize;
int plane_height = height >> (plane ? v_chroma_shift : 0);
for (int y = 0; y < plane_height; y++) {
int pos_frame = y * frame_rowsize;
int pos_pic = y * pic_rowsize;
memcpy(pic->data[plane] + pos_pic, frame->data[plane] + pos_frame, bytes);
}
}
}
#define SEC_TO_NSEC 1000000000LL
#define TIMEOUT_MAX_SEC 5
#define TIMEOUT_MAX_NSEC (TIMEOUT_MAX_SEC * SEC_TO_NSEC)
bool ffmpeg_video_encode(struct ffmpeg_video_encoder *enc, struct encoder_frame *frame, struct encoder_packet *packet,
bool *received_packet)
{
AVPacket av_pkt = {0};
bool timeout = false;
const int64_t cur_ts = (int64_t)os_gettime_ns();
const int64_t pause_offset = (int64_t)obs_encoder_get_pause_offset(enc->encoder);
int got_packet;
int ret;
if (!enc->start_ts)
enc->start_ts = cur_ts;
copy_data(enc->vframe, frame, enc->height, enc->context->pix_fmt);
enc->vframe->pts = frame->pts;
ret = avcodec_send_frame(enc->context, enc->vframe);
if (ret == 0)
ret = avcodec_receive_packet(enc->context, &av_pkt);
got_packet = (ret == 0);
if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
ret = 0;
if (ret < 0) {
warn("%s: Error encoding: %s", __func__, av_err2str(ret));
return false;
}
if (got_packet && av_pkt.size) {
if (enc->on_first_packet && enc->first_packet) {
enc->on_first_packet(enc->parent, &av_pkt, &enc->buffer.da);
enc->first_packet = false;
} else {
da_copy_array(enc->buffer, av_pkt.data, av_pkt.size);
}
packet->pts = av_pkt.pts;
packet->dts = av_pkt.dts;
packet->data = enc->buffer.array;
packet->size = enc->buffer.num;
packet->type = OBS_ENCODER_VIDEO;
packet->keyframe = !!(av_pkt.flags & AV_PKT_FLAG_KEY);
*received_packet = true;
const int64_t recv_ts_nsec = (int64_t)util_mul_div64((uint64_t)av_pkt.pts, (uint64_t)SEC_TO_NSEC,
(uint64_t)enc->context->time_base.den) +
enc->start_ts;
#if 0
debug("cur: %lld, packet: %lld, diff: %lld", cur_ts,
recv_ts_nsec, cur_ts - recv_ts_nsec);
#endif
if ((cur_ts - recv_ts_nsec - pause_offset) > TIMEOUT_MAX_NSEC) {
char timeout_str[16];
snprintf(timeout_str, sizeof(timeout_str), "%d", TIMEOUT_MAX_SEC);
struct dstr error_text = {0};
dstr_copy(&error_text, obs_module_text("Encoder.Timeout"));
dstr_replace(&error_text, "%1", enc->enc_name);
dstr_replace(&error_text, "%2", timeout_str);
obs_encoder_set_last_error(enc->encoder, error_text.array);
dstr_free(&error_text);
error("Encoding queue duration surpassed %d "
"seconds, terminating encoder",
TIMEOUT_MAX_SEC);
timeout = true;
}
} else {
*received_packet = false;
}
av_packet_unref(&av_pkt);
return !timeout;
}
| 8,785 |
C
|
.c
| 234 | 34.542735 | 118 | 0.68434 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,501 |
obs-ffmpeg-compat.h
|
obsproject_obs-studio/plugins/obs-ffmpeg/obs-ffmpeg-compat.h
|
#pragma once
#include <libavcodec/avcodec.h>
/* LIBAVCODEC_VERSION_CHECK checks for the right version of libav and FFmpeg
* a is the major version
* b and c the minor and micro versions of libav
* d and e the minor and micro versions of FFmpeg */
#define LIBAVCODEC_VERSION_CHECK(a, b, c, d, e) \
((LIBAVCODEC_VERSION_MICRO < 100 && LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(a, b, c)) || \
(LIBAVCODEC_VERSION_MICRO >= 100 && LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(a, d, e)))
| 535 |
C
|
.c
| 9 | 57.555556 | 99 | 0.650763 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,509 |
mp4-mux.c
|
obsproject_obs-studio/plugins/obs-outputs/mp4-mux.c
|
/******************************************************************************
Copyright (C) 2024 by Dennis Sädtler <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include "mp4-mux-internal.h"
#include "rtmp-hevc.h"
#include "rtmp-av1.h"
#include <obs-avc.h>
#include <obs-hevc.h>
#include <obs-module.h>
#include <util/dstr.h>
#include <util/platform.h>
#include <util/array-serializer.h>
#include <time.h>
/*
* (Mostly) compliant MP4 muxer for fun and profit.
* Based on ISO/IEC 14496-12 and FFmpeg's libavformat/movenc.c ([L]GPL)
*
* Specification section numbers are noted where applicable.
* Standard identifier is included if not referring to ISO/IEC 14496-12.
*/
#define do_log(level, format, ...) \
blog(level, "[mp4 muxer: '%s'] " format, obs_output_get_name(mux->output), ##__VA_ARGS__)
#define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
#define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
/* Helper to overwrite placeholder size and return total size. */
static inline size_t write_box_size(struct serializer *s, int64_t start)
{
int64_t end = serializer_get_pos(s);
size_t size = end - start;
serializer_seek(s, start, SERIALIZE_SEEK_START);
s_wb32(s, (uint32_t)size);
serializer_seek(s, end, SERIALIZE_SEEK_START);
return size;
}
/// 4.2 Box header with size and char[4] name
static inline void write_box(struct serializer *s, const size_t size, const char name[4])
{
if (size <= UINT32_MAX) {
s_wb32(s, (uint32_t)size); // size
s_write(s, name, 4); // boxtype
} else {
s_wb32(s, 1); // size
s_write(s, name, 4); // boxtype
s_wb64(s, size); // largesize
}
}
/// 4.2 FullBox extended header with u8 version and u24 flags
static inline void write_fullbox(struct serializer *s, const size_t size, const char name[4], uint8_t version,
uint32_t flags)
{
write_box(s, size, name);
s_w8(s, version);
s_wb24(s, flags);
}
/// 4.3 File Type Box
static size_t mp4_write_ftyp(struct mp4_mux *mux, bool fragmented)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, "ftyp");
const char *major_brand = "isom";
/* Following FFmpeg's example, when using negative CTS the major brand
* needs to be either iso4 or iso6 depending on whether the file is
* currently fragmented. */
if (mux->flags & MP4_USE_NEGATIVE_CTS)
major_brand = fragmented ? "iso6" : "iso4";
s_write(s, major_brand, 4); // major brand
s_wb32(s, 512); // minor version
// minor brands (first one matches major brand)
s_write(s, major_brand, 4);
/* Write isom base brand if it's not the major brand */
if (strcmp(major_brand, "isom") != 0)
s_write(s, "isom", 4);
/* Avoid adding newer brand (iso6) unless necessary, use "obs1" brand
* as a placeholder to maintain ftyp box size. */
if (fragmented && strcmp(major_brand, "iso6") != 0)
s_write(s, "iso6", 4);
else
s_write(s, "obs1", 4);
s_write(s, "iso2", 4);
/* Include H.264 brand if used */
for (size_t i = 0; i < mux->tracks.num; i++) {
struct mp4_track *track = &mux->tracks.array[i];
if (track->type == TRACK_VIDEO) {
if (track->codec == CODEC_H264)
s_write(s, "avc1", 4);
break;
}
}
/* General MP4 brannd */
s_write(s, "mp41", 4);
return write_box_size(s, start);
}
/// 8.1.2 Free Space Box
static size_t mp4_write_free(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
/* Write a 16-byte free box, so it can be replaced with a 64-bit size
* box header (u32 + char[4] + u64) */
s_wb32(s, 16);
s_write(s, "free", 4);
s_wb64(s, 0);
return 16;
}
/// 8.2.2 Movie Header Box
static size_t mp4_write_mvhd(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
size_t start = serializer_get_pos(s);
/* Use primary video track as the baseline for duration */
uint64_t duration = 0;
for (size_t i = 0; i < mux->tracks.num; i++) {
struct mp4_track *track = &mux->tracks.array[i];
if (track->type == TRACK_VIDEO) {
duration = util_mul_div64(track->duration, 1000, track->timebase_den);
break;
}
}
write_fullbox(s, 0, "mvhd", 0, 0);
if (duration > UINT32_MAX || mux->creation_time > UINT32_MAX) {
s_wb64(s, mux->creation_time); // creation time
s_wb64(s, mux->creation_time); // modification time
s_wb32(s, 1000); // timescale
s_wb64(s, duration); // duration (0 for fragmented)
} else {
s_wb32(s, (uint32_t)mux->creation_time); // creation time
s_wb32(s, (uint32_t)mux->creation_time); // modification time
s_wb32(s, 1000); // timescale
s_wb32(s, (uint32_t)duration); // duration (0 for fragmented)
}
s_wb32(s, 0x00010000); // rate, 16.16 fixed float (1 << 16)
s_wb16(s, 0x0100); // volume
s_wb16(s, 0); // reserved
s_wb32(s, 0); // reserved
s_wb32(s, 0); // reserved
// Matrix
for (int i = 0; i < 9; i++)
s_wb32(s, UNITY_MATRIX[i]);
// pre_defined
s_wb32(s, 0);
s_wb32(s, 0);
s_wb32(s, 0);
s_wb32(s, 0);
s_wb32(s, 0);
s_wb32(s, 0);
s_wb32(s, mux->track_ctr + 1); // next_track_ID
return write_box_size(s, start);
}
/// 8.3.2 Track Header Box
static size_t mp4_write_tkhd(struct mp4_mux *mux, struct mp4_track *track)
{
struct serializer *s = mux->serializer;
size_t start = serializer_get_pos(s);
uint64_t duration = util_mul_div64(track->duration, 1000, track->timebase_den);
/* Flags are 0x1 (enabled) | 0x2 (in movie) */
static const uint32_t flags = 0x1 | 0x2;
write_fullbox(s, 0, "tkhd", 0, flags);
if (duration > UINT32_MAX || mux->creation_time > UINT32_MAX) {
s_wb64(s, mux->creation_time); // creation time
s_wb64(s, mux->creation_time); // modification time
s_wb32(s, track->track_id); // track_id
s_wb32(s, 0); // reserved
s_wb64(s, duration); // duration in movie timescale
} else {
s_wb32(s, (uint32_t)mux->creation_time); // creation time
s_wb32(s, (uint32_t)mux->creation_time); // modification time
s_wb32(s, track->track_id); // track_id
s_wb32(s, 0); // reserved
s_wb32(s, (uint32_t)duration); // duration in movie timescale
}
s_wb32(s, 0); // reserved
s_wb32(s, 0); // reserved
s_wb16(s, 0); // layer
s_wb16(s, track->type == TRACK_AUDIO ? 1 : 0); // alternate group
s_wb16(s, track->type == TRACK_AUDIO ? 0x100 : 0); // volume
s_wb16(s, 0); // reserved
// Matrix (predefined)
for (int i = 0; i < 9; i++)
s_wb32(s, UNITY_MATRIX[i]);
if (track->type == TRACK_AUDIO) {
s_wb32(s, 0); // width
s_wb32(s, 0); // height
} else {
/* width/height are fixed point 16.16, so we just shift the
* integer to the upper 16 bits */
uint32_t width = obs_encoder_get_width(track->encoder);
s_wb32(s, width << 16);
uint32_t height = obs_encoder_get_height(track->encoder);
s_wb32(s, height << 16);
}
return write_box_size(s, start);
}
/// 8.4.2 Media Header Box
static size_t mp4_write_mdhd(struct mp4_mux *mux, struct mp4_track *track)
{
struct serializer *s = mux->serializer;
size_t size = 32;
uint8_t version = 0;
uint64_t duration = track->duration;
uint32_t timescale = track->timescale;
if (track->type == TRACK_VIDEO) {
/* Update to track timescale */
duration = util_mul_div64(duration, track->timescale, track->timebase_den);
}
/* use 64-bit duration if necessary */
if (duration > UINT32_MAX || mux->creation_time > UINT32_MAX) {
size = 44;
version = 1;
}
write_fullbox(s, size, "mdhd", version, 0);
if (version == 1) {
s_wb64(s, mux->creation_time); // creation time
s_wb64(s, mux->creation_time); // modification time
s_wb32(s, timescale); // timescale
s_wb64(s, (uint32_t)duration); // duration
} else {
s_wb32(s, (uint32_t)mux->creation_time); // creation time
s_wb32(s, (uint32_t)mux->creation_time); // modification time
s_wb32(s, timescale); // timescale
s_wb32(s, (uint32_t)duration); // duration
}
s_wb16(s, 21956); // language (undefined)
s_wb16(s, 0); // pre_defined
return size;
}
/// 8.4.3 Handler Reference Box
static size_t mp4_write_hdlr(struct mp4_mux *mux, struct mp4_track *track)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_fullbox(s, 0, "hdlr", 0, 0);
s_wb32(s, 0); // pre_defined
// handler_type
if (track->type == TRACK_VIDEO)
s_write(s, "vide", 4);
else if (track->type == TRACK_CHAPTERS)
s_write(s, "text", 4);
else
s_write(s, "soun", 4);
s_wb32(s, 0); // reserved
s_wb32(s, 0); // reserved
s_wb32(s, 0); // reserved
// name (utf-8 string, null terminated)
if (track->type == TRACK_VIDEO)
s_write(s, "OBS Video Handler", 18);
else if (track->type == TRACK_CHAPTERS)
s_write(s, "OBS Chapter Handler", 20);
else
s_write(s, "OBS Audio Handler", 18);
return write_box_size(s, start);
}
/// 12.1.2 Video media header
static size_t mp4_write_vmhd(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
/* Flags is always 1 */
write_fullbox(s, 20, "vmhd", 0, 1);
s_wb16(s, 0); // graphicsmode
s_wb16(s, 0); // opcolor r
s_wb16(s, 0); // opcolor g
s_wb16(s, 0); // opcolor b
return 16;
}
/// 12.2.2 Sound media header
static size_t mp4_write_smhd(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
write_fullbox(s, 16, "smhd", 0, 0);
s_wb16(s, 0); // balance
s_wb16(s, 0); // reserved
return 16;
}
/// (QTFF/Apple) Text media information atom
static size_t mp4_write_qt_text(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, "text");
/* Identity matrix, note that it's not fixed point 16.16 */
s_wb16(s, 0x01);
s_wb32(s, 0x00);
s_wb32(s, 0x00);
s_wb32(s, 0x00);
s_wb32(s, 0x01);
s_wb32(s, 0x00);
s_wb32(s, 0x00);
s_wb32(s, 0x00);
s_wb32(s, 0x00004000);
/* Seemingly undocumented */
s_wb16(s, 0x0000);
return write_box_size(s, start);
}
/// (QTFF/Apple) Base media info atom
static size_t mp4_write_gmin(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_fullbox(s, 0, "gmin", 0, 0);
s_wb16(s, 0x40); // graphics mode
s_wb16(s, 0x8000); // opColor r
s_wb16(s, 0x8000); // opColor g
s_wb16(s, 0x8000); // opColor b
s_wb16(s, 0); // balance
s_wb16(s, 0); // reserved
return write_box_size(s, start);
}
/// (QTFF/Apple) Base media information header atom
static size_t mp4_write_gmhd(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, "gmhd");
// gmin
mp4_write_gmin(mux);
// text (QuickTime)
mp4_write_qt_text(mux);
return write_box_size(s, start);
}
/// ISO/IEC 14496-15 5.4.2.1 AVCConfigurationBox
static size_t mp4_write_avcC(struct mp4_mux *mux, obs_encoder_t *enc)
{
struct serializer *s = mux->serializer;
/* For AVC this is the parsed extra data. */
uint8_t *header;
size_t size;
struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO, .timebase_den = 1, .keyframe = true};
if (!obs_encoder_get_extra_data(enc, &header, &size))
return 0;
packet.size = obs_parse_avc_header(&packet.data, header, size);
size_t box_size = packet.size + 8;
write_box(s, box_size, "avcC");
s_write(s, packet.data, packet.size);
bfree(packet.data);
return box_size;
}
/// ISO/IEC 14496-15 8.4.1.1 HEVCConfigurationBox
static size_t mp4_write_hvcC(struct mp4_mux *mux, obs_encoder_t *enc)
{
struct serializer *s = mux->serializer;
/* For HEVC this is the parsed extra data. */
uint8_t *header;
size_t size;
struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO, .timebase_den = 1, .keyframe = true};
if (!obs_encoder_get_extra_data(enc, &header, &size))
return 0;
packet.size = obs_parse_hevc_header(&packet.data, header, size);
size_t box_size = packet.size + 8;
write_box(s, box_size, "hvcC");
s_write(s, packet.data, packet.size);
bfree(packet.data);
return box_size;
}
/// AV1 ISOBMFF 2.3. AV1 Codec Configuration Box
static size_t mp4_write_av1C(struct mp4_mux *mux, obs_encoder_t *enc)
{
struct serializer *s = mux->serializer;
/* For AV1 this is just the parsed extra data. */
uint8_t *header;
size_t size;
struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO, .timebase_den = 1, .keyframe = true};
if (!obs_encoder_get_extra_data(enc, &header, &size))
return 0;
packet.size = obs_parse_av1_header(&packet.data, header, size);
size_t box_size = packet.size + 8;
write_box(s, box_size, "av1C");
s_write(s, packet.data, packet.size);
bfree(packet.data);
return box_size;
}
/// 12.1.5 Colour information
static size_t mp4_write_colr(struct mp4_mux *mux, obs_encoder_t *enc)
{
UNUSED_PARAMETER(enc);
struct serializer *s = mux->serializer;
write_box(s, 19, "colr");
uint8_t full_range = 0;
uint16_t pri, trc, spc;
pri = trc = spc = 0;
get_colour_information(enc, &pri, &trc, &spc, &full_range);
s_write(s, "nclx", 4); // colour_type
s_wb16(s, pri); // colour_primaries
s_wb16(s, trc); // transfer_characteristics
s_wb16(s, spc); // matrix_coefficiencts
s_w8(s, full_range << 7); // full range flag + 7 reserved bits (0)
return 19;
}
/// 12.1.4 Pixel Aspect Ratio
static size_t mp4_write_pasp(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
write_box(s, 16, "pasp");
s_wb32(s, 1); // hSpacing
s_wb32(s, 1); // vSpacing
return 16;
}
/// 12.1.3 Visual Sample Entry
static inline void mp4_write_visual_sample_entry(struct mp4_mux *mux, obs_encoder_t *enc)
{
struct serializer *s = mux->serializer;
// SampleEntry Box
s_w8(s, 0); // reserved
s_w8(s, 0);
s_w8(s, 0);
s_w8(s, 0);
s_w8(s, 0);
s_w8(s, 0);
s_wb16(s, 1); // data_reference_index
// VisualSampleEntry Box
s_wb16(s, 0); // pre_defined
s_wb16(s, 0); // reserved
s_wb32(s, 0); // pre_defined
s_wb32(s, 0); // pre_defined
s_wb32(s, 0); // pre_defined
s_wb16(s, (uint16_t)obs_encoder_get_width(enc)); // width
s_wb16(s, (uint16_t)obs_encoder_get_height(enc)); // height
s_wb32(s, 0x00480000); // horizresolution (predefined)
s_wb32(s, 0x00480000); // vertresolution (predefined)
s_wb32(s, 0); // reserved
s_wb16(s, 1); // frame_count
/* Name is fixed 32-bytes and needs to be padded to that length.
* First byte is the length, rest is a string sans NULL terminator. */
char compressor_name[32] = {0};
const char *enc_id = obs_encoder_get_id(enc);
if (enc_id) {
size_t len = strlen(enc_id);
if (len > 31)
len = 31;
compressor_name[0] = (char)len;
memcpy(compressor_name + 1, enc_id, len);
}
s_write(s, compressor_name, sizeof(compressor_name)); // compressorname
s_wb16(s, 0x0018); // depth
s_wb16(s, -1); // pre_defined
}
/// 12.1.6 Content light level
static size_t mp4_write_clli(struct mp4_mux *mux, obs_encoder_t *enc)
{
struct serializer *s = mux->serializer;
video_t *video = obs_encoder_video(enc);
const struct video_output_info *info = video_output_get_info(video);
/* Only write box for HDR video */
if (info->colorspace != VIDEO_CS_2100_PQ && info->colorspace != VIDEO_CS_2100_HLG)
return 0;
write_box(s, 12, "clli");
float nominal_peak = obs_get_video_hdr_nominal_peak_level();
s_wb16(s, (uint16_t)nominal_peak); // max_content_light_level
s_wb16(s, (uint16_t)nominal_peak); // max_pic_average_light_level
return 12;
}
/// 12.1.7 Mastering display colour volume
static size_t mp4_write_mdcv(struct mp4_mux *mux, obs_encoder_t *enc)
{
struct serializer *s = mux->serializer;
video_t *video = obs_encoder_video(enc);
const struct video_output_info *info = video_output_get_info(video);
// Only write atom for HDR video
if (info->colorspace != VIDEO_CS_2100_PQ && info->colorspace != VIDEO_CS_2100_HLG)
return 0;
write_box(s, 32, "mdcv");
float nominal_peak = obs_get_video_hdr_nominal_peak_level();
uint32_t max_lum = (uint32_t)nominal_peak * 10000;
/* Note that these values are hardcoded everywhere in OBS, so these are
* just the same as used in our other muxers/encoders. */
// 3 x display_primaries (x, y) pairs
s_wb16(s, 13250);
s_wb16(s, 34500);
s_wb16(s, 7500);
s_wb16(s, 3000);
s_wb16(s, 34000);
s_wb16(s, 16000);
s_wb16(s, 15635); // white_point_x
s_wb16(s, 16450); // white_point_y
s_wb32(s, max_lum); // max_display_mastering_luminance
s_wb32(s, 0); // min_display_mastering_luminance
return 32;
}
/// ISO/IEC 14496-15 5.4.2.1 AVCSampleEntry
static size_t mp4_write_avc1(struct mp4_mux *mux, obs_encoder_t *enc)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, "avc1");
mp4_write_visual_sample_entry(mux, enc);
// avcC
mp4_write_avcC(mux, enc);
// colr
mp4_write_colr(mux, enc);
// pasp
mp4_write_pasp(mux);
return write_box_size(s, start);
}
/// ISO/IEC 14496-15 8.4.1.1 HEVCSampleEntry
static size_t mp4_write_hvc1(struct mp4_mux *mux, obs_encoder_t *enc)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, "hvc1");
mp4_write_visual_sample_entry(mux, enc);
// avcC
mp4_write_hvcC(mux, enc);
// colr
mp4_write_colr(mux, enc);
// clli
mp4_write_clli(mux, enc);
// mdcv
mp4_write_mdcv(mux, enc);
// pasp
mp4_write_pasp(mux);
return write_box_size(s, start);
}
/// AV1 ISOBMFF 2.2. AV1 Sample Entry
static size_t mp4_write_av01(struct mp4_mux *mux, obs_encoder_t *enc)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, "av01");
mp4_write_visual_sample_entry(mux, enc);
// avcC
mp4_write_av1C(mux, enc);
// colr
mp4_write_colr(mux, enc);
// clli
mp4_write_clli(mux, enc);
// mdcv
mp4_write_mdcv(mux, enc);
// pasp
mp4_write_pasp(mux);
return write_box_size(s, start);
}
static inline void put_descr(struct serializer *s, uint8_t tag, size_t size)
{
int i = 3;
s_w8(s, tag);
for (; i > 0; i--)
s_w8(s, (uint8_t)((size >> (7 * i)) | 0x80));
s_w8(s, size & 0x7F);
}
/// ISO/IEC 14496-14 5.6 ESDBox
static size_t mp4_write_esds(struct mp4_mux *mux, struct mp4_track *track)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_fullbox(s, 0, "esds", 0, 0);
/* Encoder extradata will be used as DecoderSpecificInfo */
uint8_t *extradata;
size_t extradata_size;
if (!obs_encoder_get_extra_data(track->encoder, &extradata, &extradata_size)) {
extradata_size = 0;
}
/// ISO/IEC 14496-1
// ES_Descriptor
size_t decoder_specific_info_len = extradata_size ? extradata_size + 5 : 0;
put_descr(s, 0x03, 3 + 5 + 13 + decoder_specific_info_len + 5 + 1);
s_wb16(s, track->track_id);
s_w8(s, 0x00); // flags
// DecoderConfigDescriptor
put_descr(s, 0x04, 13 + decoder_specific_info_len);
s_w8(s, 0x40); // codec tag, 0x40 = AAC
s_w8(s, 0x15); // stream type field (0x15 = audio stream)
/* When writing the final MOOV this could theoretically be calculated
* based on chunks, but it's not really all that important. */
uint32_t bitrate = 0;
obs_data_t *settings = obs_encoder_get_settings(track->encoder);
if (settings) {
int64_t enc_bitrate = obs_data_get_int(settings, "bitrate");
if (enc_bitrate)
bitrate = (uint32_t)(enc_bitrate * 1000);
obs_data_release(settings);
}
s_wb24(s, 0); // bufferSizeDB (in bytes)
s_wb32(s, bitrate); // maxbitrate
s_wb32(s, bitrate); // avgBitrate
// DecoderSpecificInfo
if (extradata_size) {
put_descr(s, 0x05, extradata_size);
s_write(s, extradata, extradata_size);
}
// SLConfigDescriptor descriptor
put_descr(s, 0x06, 1);
s_w8(s, 0x02); // 0x2 = reserved for MP4, descriptor is empty
return write_box_size(s, start);
}
/// 12.2.3 Audio Sample Entry
static inline void mp4_write_audio_sample_entry(struct mp4_mux *mux, struct mp4_track *track, uint8_t version)
{
struct serializer *s = mux->serializer;
// SampleEntry Box
s_w8(s, 0); // reserved
s_w8(s, 0);
s_w8(s, 0);
s_w8(s, 0);
s_w8(s, 0);
s_w8(s, 0);
s_wb16(s, 1); // data_reference_index
// AudioSampleEntry Box
if (version == 1) {
s_wb16(s, 1); // entry_version
s_wb16(s, 0); // reserved
s_wb16(s, 0); // reserved
s_wb16(s, 0); // reserved
} else {
s_wb32(s, 0); // reserved
s_wb32(s, 0); // reserved
}
audio_t *audio = obs_encoder_audio(track->encoder);
size_t channels = audio_output_get_channels(audio);
uint32_t sample_rate = track->timescale;
bool alac = track->codec == CODEC_ALAC;
s_wb16(s, (uint32_t)channels); // channelcount
/* OBS FLAC is currently always 16 bit, ALAC always 24, this may change
* in the futrure and should be handled differently then.
* That being said thoes codecs are self-describing so in most cases it
* shouldn't matter either way. */
s_wb16(s, alac ? 24 : 16); // samplesize
s_wb16(s, 0); // pre_defined
s_wb16(s, 0); // reserved
s_wb32(s, sample_rate << 16); // samplerate
}
/// 12.2.4 Channel layout
static size_t mp4_write_chnl(struct mp4_mux *mux, struct mp4_track *track)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_fullbox(s, 0, "chnl", 0, 0);
audio_t *audio = obs_encoder_audio(track->encoder);
const struct audio_output_info *info = audio_output_get_info(audio);
s_w8(s, 1); // stream_structure (1 = channels)
/* 5.1 and 4.1 do not have a corresponding ISO layout, so we have to
* write a manually created channel map for those. */
uint8_t map[8] = {0};
uint8_t items = 0;
uint8_t defined_layout = 0;
get_speaker_positions(info->speakers, map, &items, &defined_layout);
if (!defined_layout) {
warn("No ISO layout available for speaker layout %d, "
"this may not be supported by all applications!",
info->speakers);
s_w8(s, 0); // definedLayout
s_write(s, map, items); // uint8_t speaker_position[count]
} else {
s_w8(s, defined_layout); // definedLayout
s_wb64(s, 0); // ommitedChannelMap
}
return write_box_size(s, start);
}
/// ISO/IEC 14496-14 5.6 MP4AudioSampleEntry
static size_t mp4_write_mp4a(struct mp4_mux *mux, struct mp4_track *track, uint8_t version)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, "mp4a");
mp4_write_audio_sample_entry(mux, track, version);
// esds
mp4_write_esds(mux, track);
/* Write channel layout for version 1 sample entires */
if (version == 1)
mp4_write_chnl(mux, track);
return write_box_size(s, start);
}
/// Encapsulation of FLAC in ISO Base Media File Format 3.3.2 FLAC Specific Box
static size_t mp4_write_dfLa(struct mp4_mux *mux, struct mp4_track *track)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
uint8_t *extradata;
size_t extradata_size;
if (!obs_encoder_get_extra_data(track->encoder, &extradata, &extradata_size))
return 0;
write_fullbox(s, 0, "dfLa", 0, 0);
/// FLACMetadataBlock
// LastMetadataBlockFlag (1) | BlockType (0)
s_w8(s, 1 << 7 | 0);
// Length
s_wb24(s, (uint32_t)extradata_size);
// BlockData[Length]
s_write(s, extradata, extradata_size);
return write_box_size(s, start);
}
/// Encapsulation of FLAC in ISO Base Media File Format 3.3.1 FLACSampleEntry
static size_t mp4_write_fLaC(struct mp4_mux *mux, struct mp4_track *track, uint8_t version)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, "fLaC");
mp4_write_audio_sample_entry(mux, track, version);
// dfLa
mp4_write_dfLa(mux, track);
if (version == 1)
mp4_write_chnl(mux, track);
return write_box_size(s, start);
}
/// Apple Lossless Format "Magic Cookie" Description - MP4/M4A File
static size_t mp4_write_alac(struct mp4_mux *mux, struct mp4_track *track, uint8_t version)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
uint8_t *extradata;
size_t extradata_size;
if (!obs_encoder_get_extra_data(track->encoder, &extradata, &extradata_size))
return 0;
write_box(s, 0, "alac");
mp4_write_audio_sample_entry(mux, track, version);
/* Apple Lossless Magic Cookie */
s_write(s, extradata, extradata_size);
if (version == 1)
mp4_write_chnl(mux, track);
return write_box_size(s, start);
}
/// ISO/IEC 23003-5 5.1 PCM configuration
static size_t mp4_write_pcmc(struct mp4_mux *mux, struct mp4_track *track)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_fullbox(s, 0, "pcmC", 0, 0);
s_w8(s, 1); // endianness, 1 = little endian
// bits per sample
if (track->codec == CODEC_PCM_I16)
s_w8(s, 16);
else if (track->codec == CODEC_PCM_I24)
s_w8(s, 24);
else if (track->codec == CODEC_PCM_F32)
s_w8(s, 32);
return write_box_size(s, start);
}
/// ISO/IEC 23003-5 5.1 PCM configuration
static size_t mp4_write_xpcm(struct mp4_mux *mux, struct mp4_track *track, uint8_t version)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
/* Different box types for floating point and integer PCM*/
write_box(s, 0, track->codec == CODEC_PCM_F32 ? "fpcm" : "ipcm");
mp4_write_audio_sample_entry(mux, track, version);
/* ChannelLayout (chnl) is required for PCM */
mp4_write_chnl(mux, track);
// pcmc
mp4_write_pcmc(mux, track);
return write_box_size(s, start);
}
/// (QTFF/Apple) Text sample description
static size_t mp4_write_text(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_fullbox(s, 0, "text", 0, 0);
s_wb32(s, 1); // number of entries
/* Preset sample description as used by FFmpeg. */
s_write(s, &TEXT_STUB_HEADER, sizeof(TEXT_STUB_HEADER));
return write_box_size(s, start);
}
static inline uint32_t rl32(const uint8_t *ptr)
{
return (ptr[3] << 24) + (ptr[2] << 16) + (ptr[1] << 8) + ptr[0];
}
static inline uint16_t rl16(const uint8_t *ptr)
{
return (ptr[1] << 8) + ptr[0];
}
/// Encapsulation of Opus in ISO Base Media File Format 4.3.2 Opus Specific Box
static size_t mp4_write_dOps(struct mp4_mux *mux, struct mp4_track *track)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
uint8_t *extradata;
size_t extradata_size;
if (!obs_encoder_get_extra_data(track->encoder, &extradata, &extradata_size))
return 0;
write_box(s, 0, "dOps");
s_w8(s, 0); // version
uint8_t channels = *(extradata + 9);
uint8_t channel_map = *(extradata + 18);
s_w8(s, channels); // channel count
// OpusHead is little-endian, but MP4 is big-endian, so we have to swap them here
s_wb16(s, rl16(extradata + 10)); // pre-skip
s_wb32(s, rl32(extradata + 12)); // input sample rate
s_wb16(s, rl16(extradata + 16)); // output gain
s_w8(s, channel_map); // channel mapping family
if (channel_map)
s_write(s, extradata + 19, 2 + channels);
return write_box_size(s, start);
}
/// Encapsulation of Opus in ISO Base Media File Format 4.3.1 Sample entry format
static size_t mp4_write_Opus(struct mp4_mux *mux, struct mp4_track *track, uint8_t version)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, "Opus");
mp4_write_audio_sample_entry(mux, track, version);
// dOps
mp4_write_dOps(mux, track);
if (version == 1)
mp4_write_chnl(mux, track);
return write_box_size(s, start);
}
/// 8.5.2 Sample Description Box
static size_t mp4_write_stsd(struct mp4_mux *mux, struct mp4_track *track)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
/* Anything but mono or stereo technically requires v1,
* but in practice that doesn't appear to matter. */
uint8_t version = 0;
if (track->type == TRACK_AUDIO) {
audio_t *audio = obs_encoder_audio(track->encoder);
version = audio_output_get_channels(audio) > 2 ? 1 : 0;
}
write_fullbox(s, 0, "stsd", version, 0);
s_wb32(s, 1); // entry_count
// codec specific boxes
if (track->type == TRACK_VIDEO) {
if (track->codec == CODEC_H264)
mp4_write_avc1(mux, track->encoder);
else if (track->codec == CODEC_HEVC)
mp4_write_hvc1(mux, track->encoder);
else if (track->codec == CODEC_AV1)
mp4_write_av01(mux, track->encoder);
} else if (track->type == TRACK_AUDIO) {
if (track->codec == CODEC_AAC)
mp4_write_mp4a(mux, track, version);
else if (track->codec == CODEC_OPUS)
mp4_write_Opus(mux, track, version);
else if (track->codec == CODEC_FLAC)
mp4_write_fLaC(mux, track, version);
else if (track->codec == CODEC_ALAC)
mp4_write_alac(mux, track, version);
else if (track->codec == CODEC_PCM_I16 || track->codec == CODEC_PCM_I24 ||
track->codec == CODEC_PCM_F32)
mp4_write_xpcm(mux, track, version);
} else if (track->type == TRACK_CHAPTERS) {
mp4_write_text(mux);
}
return write_box_size(s, start);
}
/// 8.6.1.2 Decoding Time to Sample Box
static size_t mp4_write_stts(struct mp4_mux *mux, struct mp4_track *track, bool fragmented)
{
struct serializer *s = mux->serializer;
if (fragmented) {
write_fullbox(s, 16, "stts", 0, 0);
s_wb32(s, 0); // entry_count
return 16;
}
int64_t start = serializer_get_pos(s);
struct sample_delta *arr = track->deltas.array;
size_t num = track->deltas.num;
write_fullbox(s, 0, "stts", 0, 0);
s_wb32(s, (uint32_t)num); // entry_count
for (size_t idx = 0; idx < num; idx++) {
struct sample_delta *smp = &arr[idx];
uint64_t delta = util_mul_div64(smp->delta, track->timescale, track->timebase_den);
s_wb32(s, smp->count); // sample_count
s_wb32(s, (uint32_t)delta); // sample_delta
}
return write_box_size(s, start);
}
/// 8.6.2 Sync Sample Box
static size_t mp4_write_stss(struct mp4_mux *mux, struct mp4_track *track)
{
struct serializer *s = mux->serializer;
uint32_t num = (uint32_t)track->sync_samples.num;
if (!num)
return 0;
/* 16 byte FullBox header + 4-bytes (u32) per sync sample */
uint32_t size = 16 + 4 * num;
write_fullbox(s, size, "stss", 0, 0);
s_wb32(s, num); // entry_count
for (size_t idx = 0; idx < num; idx++)
s_wb32(s, track->sync_samples.array[idx]); // sample_number
return size;
}
/// 8.6.1.3 Composition Time to Sample Box
static size_t mp4_write_ctts(struct mp4_mux *mux, struct mp4_track *track)
{
struct serializer *s = mux->serializer;
uint32_t num = (uint32_t)track->offsets.num;
uint8_t version = mux->flags & MP4_USE_NEGATIVE_CTS ? 1 : 0;
/* 16 byte FullBox header + 8-bytes (u32+u32/i32) per offset entry */
uint32_t size = 16 + 8 * num;
write_fullbox(s, size, "ctts", version, 0);
s_wb32(s, num); // entry_count
for (size_t idx = 0; idx < num; idx++) {
int64_t offset = (int64_t)track->offsets.array[idx].offset * (int64_t)track->timescale /
(int64_t)track->timebase_den;
s_wb32(s, track->offsets.array[idx].count); // sample_count
s_wb32(s, (uint32_t)offset); // sample_offset
}
return size;
}
/// 8.7.4 Sample To Chunk Box
static size_t mp4_write_stsc(struct mp4_mux *mux, struct mp4_track *track, bool fragmented)
{
struct serializer *s = mux->serializer;
if (fragmented) {
write_fullbox(s, 16, "stsc", 0, 0);
s_wb32(s, 0); // entry_count
return 16;
}
struct chunk *arr = track->chunks.array;
size_t arr_num = track->chunks.num;
/* Compress into array with counter for repeating chunk sizes */
DARRAY(struct chunk_run {
uint32_t first;
uint32_t samples;
}) chunk_runs;
da_init(chunk_runs);
for (size_t idx = 0; idx < arr_num; idx++) {
struct chunk *chk = &arr[idx];
if (!chunk_runs.num || chunk_runs.array[chunk_runs.num - 1].samples != chk->samples) {
struct chunk_run *cr = da_push_back_new(chunk_runs);
cr->samples = chk->samples;
cr->first = (uint32_t)idx + 1; // ISO-BMFF is 1-indexed
}
}
uint32_t num = (uint32_t)chunk_runs.num;
/* 16 byte FullBox header + 12-bytes (u32+u32+u32) per chunk run */
uint32_t size = 16 + 12 * num;
write_fullbox(s, size, "stsc", 0, 0);
s_wb32(s, num); // entry_count
for (size_t idx = 0; idx < num; idx++) {
struct chunk_run *cr = &chunk_runs.array[idx];
s_wb32(s, cr->first); // first_chunk
s_wb32(s, cr->samples); // samples_per_chunk
s_wb32(s, 1); // sample_description_index
}
da_free(chunk_runs);
return size;
}
/// 8.7.3 Sample Size Boxes
static size_t mp4_write_stsz(struct mp4_mux *mux, struct mp4_track *track, bool fragmented)
{
struct serializer *s = mux->serializer;
if (fragmented) {
write_fullbox(s, 20, "stsz", 0, 0);
s_wb32(s, 0); // sample_size
s_wb32(s, 0); // sample_count
return 20;
}
int64_t start = serializer_get_pos(s);
/* This should only ever happen when recording > 24 hours of
* 48 kHz PCM audio or 828 days of 60 FPS video. */
if (track->samples > UINT32_MAX) {
warn("Track %u has too many samples, its duration may not be "
"read correctly. Remuxing the file to another format such "
"as MKV may be required.",
track->track_id);
}
write_fullbox(s, 0, "stsz", 0, 0);
if (track->sample_size) {
/* Fixed size samples mean we don't need an array */
s_wb32(s, track->sample_size); // sample_size
s_wb32(s, (uint32_t)track->samples); // sample_count
} else {
s_wb32(s, 0); // sample_size
s_wb32(s, (uint32_t)track->sample_sizes.num); // sample_count
for (size_t idx = 0; idx < track->sample_sizes.num; idx++) {
s_wb32(s, track->sample_sizes.array[idx]); // entry_size
}
}
return write_box_size(s, start);
}
/// 8.7.5 Chunk Offset Box
static size_t mp4_write_stco(struct mp4_mux *mux, struct mp4_track *track, bool fragmented)
{
struct serializer *s = mux->serializer;
if (fragmented) {
write_fullbox(s, 16, "stco", 0, 0);
s_wb32(s, 0); // entry_count
return 16;
}
struct chunk *arr = track->chunks.array;
uint32_t num = (uint32_t)track->chunks.num;
uint64_t last_off = arr[num - 1].offset;
uint32_t size;
bool co64 = last_off > UINT32_MAX;
/* When using 64-bit offsets we write 8-bytes (u64) per chunk,
* otherwise 4-bytes (u32). */
if (co64) {
size = 16 + 8 * num;
write_fullbox(s, size, "co64", 0, 0);
} else {
size = 16 + 4 * num;
write_fullbox(s, size, "stco", 0, 0);
}
s_wb32(s, num); // entry_count
for (size_t idx = 0; idx < num; idx++) {
if (co64)
s_wb64(s, arr[idx].offset); // chunk_offset
else
s_wb32(s, (uint32_t)arr[idx].offset); // chunk_offset
}
return size;
}
/// 8.9.3 Sample Group Description Box
static size_t mp4_write_sgpd_aac(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_fullbox(s, 0, "sgpd", 1, 0);
s_write(s, "roll", 4); // grouping_tpye
s_wb32(s, 2); // default_length (i16)
s_wb32(s, 1); // entry_count
// AudioRollRecoveryEntry
s_wb16(s, -1); // roll_distance
return write_box_size(s, start);
}
/// 8.9.2 Sample to Group Box
static size_t mp4_write_sbgp_aac(struct mp4_mux *mux, struct mp4_track *track)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_fullbox(s, 0, "sbgp", 0, 0);
/// 10.1 AudioRollRecoveryEntry
s_write(s, "roll", 4); // grouping_tpye
s_wb32(s, 1); // entry_count
s_wb32(s, (uint32_t)track->samples); // sample_count
s_wb32(s, 1); // group_description_index
return write_box_size(s, start);
}
static size_t mp4_write_sbgp_sbgp_opus(struct mp4_mux *mux, struct mp4_track *track)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
/// 8.9.3 Sample Group Description Box
write_fullbox(s, 0, "sgpd", 1, 0);
s_write(s, "roll", 4); // grouping_tpye
s_wb32(s, 2); // default_length (i16)
/* Opus requires 80 ms of preroll, which at 48 kHz is 3840 PCM samples */
const int64_t opus_preroll = 3840;
/* Compute the preroll samples (should be 4, each being 20 ms) */
uint16_t preroll_count = 0;
int64_t preroll_remaining = opus_preroll;
for (size_t i = 0; i < track->deltas.num && preroll_remaining > 0; i++) {
for (uint32_t j = 0; j < track->deltas.array[i].count && preroll_remaining > 0; j++) {
preroll_remaining -= track->deltas.array[i].delta;
preroll_count++;
}
}
s_wb32(s, 1); // entry_count
/// 10.1 AudioRollRecoveryEntry
s_wb16(s, -preroll_count); // roll_distance
size_t size_sgpd = write_box_size(s, start);
/* --------------- */
/// 8.9.2 Sample to Group Box
start = serializer_get_pos(s);
write_fullbox(s, 0, "sbgp", 0, 0);
s_write(s, "roll", 4); // grouping_tpye
s_wb32(s, 2); // entry_count
// entry 0
s_wb32(s, preroll_count); // sample_count
s_wb32(s, 0); // group_description_index
// entry 1
s_wb32(s, (uint32_t)track->samples - preroll_count); // sample_count
s_wb32(s, 1); // group_description_index
return size_sgpd + write_box_size(s, start);
}
/// 8.5.1 Sample Table Box
static size_t mp4_write_stbl(struct mp4_mux *mux, struct mp4_track *track, bool fragmented)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, "stbl");
// stsd
mp4_write_stsd(mux, track);
// stts
mp4_write_stts(mux, track, fragmented);
// stss (non-fragmented only)
if (track->type == TRACK_VIDEO && !fragmented)
mp4_write_stss(mux, track);
// ctts (non-fragmented only)
if (track->needs_ctts && !fragmented)
mp4_write_ctts(mux, track);
// stsc
mp4_write_stsc(mux, track, fragmented);
// stsz
mp4_write_stsz(mux, track, fragmented);
// stco
mp4_write_stco(mux, track, fragmented);
if (!fragmented) {
/* AAC and Opus require a pre-roll to get correct decoder
* output, sgpd and sbgp are used to create a "roll" group. */
if (track->codec == CODEC_AAC) {
// sgpd
mp4_write_sgpd_aac(mux);
// sbgp
mp4_write_sbgp_aac(mux, track);
} else if (track->codec == CODEC_OPUS) {
// sgpd + sbgp
mp4_write_sbgp_sbgp_opus(mux, track);
}
}
return write_box_size(s, start);
}
/// 8.7.2.2 DataEntryUrlBox
static size_t mp4_write_url(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_fullbox(s, 0, "url ", 0, 1);
/* empty, flag 1 means data is in this file */
return write_box_size(s, start);
}
/// 8.7.2 Data Reference Box
static size_t mp4_write_dref(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_fullbox(s, 0, "dref ", 0, 0);
s_wb32(s, 1); // entry_count
mp4_write_url(mux);
return write_box_size(s, start);
}
/// 8.7.1 Data Information Box
static size_t mp4_write_dinf(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, "dinf");
mp4_write_dref(mux);
return write_box_size(s, start);
}
/// 8.4.4 Media Information Box
static size_t mp4_write_minf(struct mp4_mux *mux, struct mp4_track *track, bool fragmented)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, "minf");
// vmhd/smhd/gmhd
if (track->type == TRACK_VIDEO)
mp4_write_vmhd(mux);
else if (track->type == TRACK_CHAPTERS)
mp4_write_gmhd(mux);
else
mp4_write_smhd(mux);
// dinf, unnecessary but mandatory
mp4_write_dinf(mux);
// stbl
mp4_write_stbl(mux, track, fragmented);
return write_box_size(s, start);
}
/// 8.4.1 Media Box
static size_t mp4_write_mdia(struct mp4_mux *mux, struct mp4_track *track, bool fragmented)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, "mdia");
// mdhd
mp4_write_mdhd(mux, track);
// hdlr
mp4_write_hdlr(mux, track);
// minf
mp4_write_minf(mux, track, fragmented);
return write_box_size(s, start);
}
/// (QTFF/Apple) User data atom
static size_t mp4_write_udta_atom(struct mp4_mux *mux, const char tag[4], const char *val)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, tag);
s_write(s, val, strlen(val));
return write_box_size(s, start);
}
/// 8.10.1 User Data Box
static size_t mp4_write_track_udta(struct mp4_mux *mux, struct mp4_track *track)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, "udta");
/* Our udta box contains QuickTime format user data atoms, which are
* simple key-value pairs. Some are prefixed with 0xa9. */
const char *name = obs_encoder_get_name(track->encoder);
if (name)
mp4_write_udta_atom(mux, "name", name);
if (mux->flags & MP4_WRITE_ENCODER_INFO) {
const char *id = obs_encoder_get_id(track->encoder);
if (name)
mp4_write_udta_atom(mux, "\251enc", id);
obs_data_t *settings = obs_encoder_get_settings(track->encoder);
if (settings) {
const char *json = obs_data_get_json_with_defaults(settings);
mp4_write_udta_atom(mux, "json", json);
obs_data_release(settings);
}
}
return write_box_size(s, start);
}
/// 8.6.6 Edit List Box
static size_t mp4_write_elst(struct mp4_mux *mux, struct mp4_track *track)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_fullbox(s, 0, "elst", 0, 0);
s_wb32(s, 1); // entry count
uint64_t duration = util_mul_div64(track->duration, 1000, track->timebase_den);
uint64_t delay = 0;
if (track->type == TRACK_VIDEO && !(mux->flags & MP4_USE_NEGATIVE_CTS)) {
/* Compensate for frame-reordering delay (for example, when
* using b-frames). */
int64_t dts_offset = 0;
if (track->offsets.num) {
struct sample_offset sample = track->offsets.array[0];
dts_offset = sample.offset;
} else if (track->packets.size) {
/* If no offset data exists yet (i.e. when writing the
* incomplete moov in a fragmented file) use the raw
* data from the current queued packets instead. */
struct encoder_packet pkt;
deque_peek_front(&track->packets, &pkt, sizeof(pkt));
dts_offset = pkt.pts - pkt.dts;
}
delay = util_mul_div64(dts_offset, track->timescale, track->timebase_den);
} else if (track->type == TRACK_AUDIO && track->first_pts < 0) {
delay = util_mul_div64(llabs(track->first_pts), track->timescale, track->timebase_den);
/* Subtract priming delay from total duration */
duration -= util_mul_div64(delay, 1000, track->timescale);
}
s_wb32(s, (uint32_t)duration); // segment_duration (movie timescale)
s_wb32(s, (uint32_t)delay); // media_time (track timescale)
s_wb32(s, 1 << 16); // media_rate
return write_box_size(s, start);
}
/// 8.6.5 Edit Box
static size_t mp4_write_edts(struct mp4_mux *mux, struct mp4_track *track)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, "edts");
mp4_write_elst(mux, track);
return write_box_size(s, start);
}
/// 8.3.3.2 TrackReferenceTypeBox
static size_t mp4_write_chap(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
/// QTFF/Apple chapter track reference
write_box(s, 0, "chap");
s_wb32(s, mux->chapter_track->track_id);
return write_box_size(s, start);
}
/// 8.3.3 Track Reference Box
static size_t mp4_write_tref(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, "tref");
mp4_write_chap(mux);
return write_box_size(s, start);
}
/// 8.3.1 Track Box
static size_t mp4_write_trak(struct mp4_mux *mux, struct mp4_track *track, bool fragmented)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
/* If track has no data, omit it from full moov. */
if (!fragmented && !track->chunks.num)
return 0;
write_box(s, 0, "trak");
// tkhd
mp4_write_tkhd(mux, track);
// edts
mp4_write_edts(mux, track);
// tref
if (mux->chapter_track && track->type != TRACK_CHAPTERS)
mp4_write_tref(mux);
// mdia
mp4_write_mdia(mux, track, fragmented);
// udta (audio track name mainly)
mp4_write_track_udta(mux, track);
return write_box_size(s, start);
}
/// 8.8.3 Track Extends Box
static size_t mp4_write_trex(struct mp4_mux *mux, uint32_t track_id)
{
struct serializer *s = mux->serializer;
write_fullbox(s, 32, "trex", 0, 0);
s_wb32(s, track_id); // track_ID
s_wb32(s, 1); // default_sample_description_index
s_wb32(s, 0); // default_sample_duration
s_wb32(s, 0); // default_sample_size
s_wb32(s, 0); // default_sample_flags
return 32;
}
/// 8.8.1 Movie Extends Box
static size_t mp4_write_mvex(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, "mvex");
for (size_t track_id = 0; track_id < mux->tracks.num; track_id++)
mp4_write_trex(mux, (uint32_t)(track_id + 1));
return write_box_size(s, start);
}
/// (QTFF/Apple) Undocumented QuickTime/iTunes metadata handler
static size_t mp4_write_itunes_hdlr(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
write_fullbox(s, 33, "hdlr", 0, 0);
s_wb32(s, 0); // pre_defined
s_write(s, "mdir", 4); // handler_type
// reserved
s_write(s, "appl", 4);
s_wb32(s, 0);
s_wb32(s, 0);
s_w8(s, 0); // name (NULL)
return 33;
}
/// (QTFF/Apple) Data atom
static size_t mp4_write_data_atom(struct mp4_mux *mux, const char *data)
{
struct serializer *s = mux->serializer;
size_t len = strlen(data);
uint32_t size = 16 + (uint32_t)len;
write_box(s, size, "data");
s_wb32(s, 1); // type, 1 = utf-8 string
s_wb32(s, 0); // locale, 0 = default
s_write(s, data, len);
return size;
}
/// (QTFF/Apple) Metadata item atom
static size_t mp4_write_ilst_item_atom(struct mp4_mux *mux, const char name[4], const char *value)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, name);
mp4_write_data_atom(mux, value);
return write_box_size(s, start);
}
/// (QTFF/Apple) Metadata item list atom
static size_t mp4_write_ilst(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
struct dstr value = {0};
int64_t start = serializer_get_pos(s);
write_box(s, 0, "ilst");
/* Encoder name */
dstr_cat(&value, "OBS Studio (");
dstr_cat(&value, obs_get_version_string());
dstr_cat(&value, ")");
/* Some QuickTime keys are prefixed with 0xa9 */
mp4_write_ilst_item_atom(mux, "\251too", value.array);
dstr_free(&value);
return write_box_size(s, start);
}
/// (QTFF/Apple) Key value metadata handler
static size_t mp4_write_mdta_hdlr(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
write_fullbox(s, 33, "hdlr", 0, 0);
s_wb32(s, 0); // pre_defined
s_write(s, "mdta", 4); // handler_type
// reserved
s_wb32(s, 0);
s_wb32(s, 0);
s_wb32(s, 0);
s_w8(s, 0); // name (NULL)
return 33;
}
/// (QTFF/Apple) Metadata item keys atom
static size_t mp4_write_mdta_keys(struct mp4_mux *mux, obs_data_t *meta)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_fullbox(s, 0, "keys", 0, 0);
uint32_t count = 0;
int64_t count_pos = serializer_get_pos(s);
s_wb32(s, count); // count
obs_data_item_t *item = obs_data_first(meta);
for (; item != NULL; obs_data_item_next(&item)) {
const char *name = obs_data_item_get_name(item);
size_t len = strlen(name);
/* name is key type, can be udta or mdta */
write_box(s, len + 8, "mdta");
s_write(s, name, len); // key name
count++;
}
int64_t end = serializer_get_pos(s);
/* Overwrite count with correct value */
serializer_seek(s, count_pos, SERIALIZE_SEEK_START);
s_wb32(s, count);
serializer_seek(s, end, SERIALIZE_SEEK_START);
return write_box_size(s, start);
}
/// (QTFF/Apple) Metadata item atom, but name is an index instead
static inline void write_key_entry(struct mp4_mux *mux, obs_data_item_t *item, uint32_t idx)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
s_wb32(s, 0); // size
s_wb32(s, idx); // index
mp4_write_data_atom(mux, obs_data_item_get_string(item));
write_box_size(s, start);
}
/// (QTFF/Apple) Metadata item list atom
static size_t mp4_write_mdta_ilst(struct mp4_mux *mux, obs_data_t *meta)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, "ilst");
/* indices start with 1 */
uint32_t key_idx = 1;
obs_data_item_t *item = obs_data_first(meta);
for (; item != NULL; obs_data_item_next(&item)) {
write_key_entry(mux, item, key_idx);
key_idx++;
}
return write_box_size(s, start);
}
static void mp4_write_mdta_kv(struct mp4_mux *mux)
{
struct dstr value = {0};
obs_data_t *meta = obs_data_create();
dstr_cat(&value, "OBS Studio (");
dstr_cat(&value, obs_get_version_string());
dstr_cat(&value, ")");
// ToDo figure out what else we could put in here for fun and profit :)
obs_data_set_string(meta, "tool", value.array);
/* Write keys */
mp4_write_mdta_keys(mux, meta);
/* Write values */
mp4_write_mdta_ilst(mux, meta);
obs_data_release(meta);
dstr_free(&value);
}
/// 8.11.1 The Meta box
static size_t mp4_write_meta(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_fullbox(s, 0, "meta", 0, 0);
if (mux->flags & MP4_USE_MDTA_KEY_VALUE) {
mp4_write_mdta_hdlr(mux);
mp4_write_mdta_kv(mux);
} else {
mp4_write_itunes_hdlr(mux);
mp4_write_ilst(mux);
}
return write_box_size(s, start);
}
/// 8.10.1 User Data Box
static size_t mp4_write_udta(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, "udta");
/* Normally metadata would be directly in the moov, but since this is
* Apple/QTFF format metadata it is inside udta. */
// meta
mp4_write_meta(mux);
return write_box_size(s, start);
}
/// Movie Box (8.2.1)
static size_t mp4_write_moov(struct mp4_mux *mux, bool fragmented)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, "moov");
mp4_write_mvhd(mux);
// trak(s)
for (size_t i = 0; i < mux->tracks.num; i++) {
struct mp4_track *track = &mux->tracks.array[i];
mp4_write_trak(mux, track, fragmented);
}
if (!fragmented && mux->chapter_track)
mp4_write_trak(mux, mux->chapter_track, false);
// mvex
if (fragmented)
mp4_write_mvex(mux);
// udta (metadata)
mp4_write_udta(mux);
return write_box_size(s, start);
}
/* ========================================================================== */
/* moof (fragment header) stuff */
/// 8.8.5 Movie Fragment Header Box
static size_t mp4_write_mfhd(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
write_fullbox(s, 16, "mfhd", 0, 0);
s_wb32(s, mux->fragments_written); // sequence_number
return 16;
}
/// 8.8.7 Track Fragment Header Box
static size_t mp4_write_tfhd(struct mp4_mux *mux, struct mp4_track *track, size_t moof_start)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
uint32_t flags = BASE_DATA_OFFSET_PRESENT | DEFAULT_SAMPLE_FLAGS_PRESENT;
/* Add default size/duration if all samples match. */
bool durations_match = true;
bool sizes_match = true;
uint32_t duration;
uint32_t sample_size;
if (track->sample_size) {
duration = 1;
sample_size = track->sample_size;
} else {
duration = track->fragment_samples.array[0].duration;
sample_size = track->fragment_samples.array[0].size;
for (size_t idx = 1; idx < track->fragment_samples.num; idx++) {
uint32_t frag_duration = track->fragment_samples.array[idx].duration;
uint32_t frag_size = track->fragment_samples.array[idx].size;
durations_match = frag_duration == duration;
sizes_match = frag_size == sample_size;
}
}
if (durations_match)
flags |= DEFAULT_SAMPLE_DURATION_PRESENT;
if (sizes_match)
flags |= DEFAULT_SAMPLE_SIZE_PRESENT;
write_fullbox(s, 0, "tfhd", 0, flags);
s_wb32(s, track->track_id); // track_ID
s_wb64(s, moof_start); // base_data_offset
// default_sample_duration
if (durations_match) {
if (track->type == TRACK_VIDEO) {
/* Convert duration to track timescale */
duration = (uint32_t)util_mul_div64(duration, track->timescale, track->timebase_den);
}
s_wb32(s, duration);
}
// default_sample_size
if (sizes_match)
s_wb32(s, sample_size);
// default_sample_flags
if (track->type == TRACK_VIDEO) {
s_wb32(s, SAMPLE_FLAG_DEPENDS_YES | SAMPLE_FLAG_IS_NON_SYNC);
} else {
s_wb32(s, SAMPLE_FLAG_DEPENDS_NO);
}
return write_box_size(s, start);
}
/// 8.8.12 Track fragment decode time
static size_t mp4_write_tfdt(struct mp4_mux *mux, struct mp4_track *track)
{
struct serializer *s = mux->serializer;
write_fullbox(s, 20, "tfdt", 1, 0);
/* Subtract samples that are not written yet */
uint64_t duration_written = track->duration;
for (size_t i = 0; i < track->fragment_samples.num; i++)
duration_written -= track->fragment_samples.array[i].duration;
if (track->type == TRACK_VIDEO) {
/* Convert to track timescale */
duration_written = util_mul_div64(duration_written, track->timescale, track->timebase_den);
}
s_wb64(s, duration_written); // baseMediaDecodeTime
return 20;
}
/// 8.8.8 Track Fragment Run Box
static size_t mp4_write_trun(struct mp4_mux *mux, struct mp4_track *track, uint32_t moof_size,
uint64_t *samples_mdat_offset)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
uint32_t flags = DATA_OFFSET_PRESENT;
if (!track->sample_size)
flags |= SAMPLE_SIZE_PRESENT;
if (track->type == TRACK_VIDEO) {
flags |= FIRST_SAMPLE_FLAGS_PRESENT;
flags |= SAMPLE_COMPOSITION_TIME_OFFSETS_PRESENT;
}
uint8_t version = mux->flags & MP4_USE_NEGATIVE_CTS ? 1 : 0;
write_fullbox(s, 0, "trun", version, flags);
/* moof_size + 8 bytes for mdat header + offset into mdat box data */
size_t data_offset = moof_size + 8 + *samples_mdat_offset;
size_t sample_count = track->fragment_samples.num;
if (track->sample_size) {
/* Update count based on fixed size */
size_t total_size = 0;
for (size_t i = 0; i < sample_count; i++)
total_size += track->fragment_samples.array[i].size;
*samples_mdat_offset += total_size;
sample_count = total_size / track->sample_size;
}
s_wb32(s, (uint32_t)sample_count); // sample_count
s_wb32(s, (uint32_t)data_offset); // data_offset
/* If we have a fixed sample size (PCM audio) we only need to write
* the sample count and offset. */
if (track->sample_size)
return write_box_size(s, start);
if (track->type == TRACK_VIDEO)
s_wb32(s, SAMPLE_FLAG_DEPENDS_NO); // first_sample_flags
for (size_t idx = 0; idx < sample_count; idx++) {
struct fragment_sample *smp = &track->fragment_samples.array[idx];
s_wb32(s, smp->size); // sample_size
if (track->type == TRACK_VIDEO) {
// sample_composition_time_offset
int64_t offset =
(int64_t)smp->offset * (int64_t)track->timescale / (int64_t)track->timebase_den;
s_wb32(s, (uint32_t)offset);
}
*samples_mdat_offset += smp->size;
}
return write_box_size(s, start);
}
/// 8.8.6 Track Fragment Box
static size_t mp4_write_traf(struct mp4_mux *mux, struct mp4_track *track, int64_t moof_start, uint32_t moof_size,
uint64_t *samples_mdat_offset)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, "traf");
// tfhd
mp4_write_tfhd(mux, track, moof_start);
// tfdt
mp4_write_tfdt(mux, track);
// trun
mp4_write_trun(mux, track, moof_size, samples_mdat_offset);
return write_box_size(s, start);
}
/// 8.8.4 Movie Fragment Box
static size_t mp4_write_moof(struct mp4_mux *mux, uint32_t moof_size, int64_t moof_start)
{
struct serializer *s = mux->serializer;
int64_t start = serializer_get_pos(s);
write_box(s, 0, "moof");
mp4_write_mfhd(mux);
/* Track current mdat offset across tracks */
uint64_t samples_mdat_offset = 0;
// traf boxes
for (size_t i = 0; i < mux->tracks.num; i++) {
struct mp4_track *track = &mux->tracks.array[i];
/* Skip tracks that do not have any samples */
if (!track->fragment_samples.num)
continue;
mp4_write_traf(mux, track, moof_start, moof_size, &samples_mdat_offset);
}
return write_box_size(s, start);
}
/* ========================================================================== */
/* Chapter packets */
static void mp4_create_chapter_pkt(struct encoder_packet *pkt, int64_t dts_usec, const char *name)
{
int64_t dts = dts_usec / 1000; // chapter track uses a ms timebase
pkt->pts = dts;
pkt->dts = dts;
pkt->dts_usec = dts_usec;
pkt->timebase_num = 1;
pkt->timebase_den = 1000;
/* Serialize with data with ref count */
struct serializer s;
struct array_output_data ao;
array_output_serializer_init(&s, &ao);
size_t len = min(strlen(name), UINT16_MAX);
long refs = 1;
/* encoder_packet refs */
s_write(&s, &refs, sizeof(refs));
/* actual packet data */
s_wb16(&s, (uint16_t)len);
s_write(&s, name, len);
s_write(&s, &CHAPTER_PKT_FOOTER, sizeof(CHAPTER_PKT_FOOTER));
pkt->data = (void *)(ao.bytes.array + sizeof(long));
pkt->size = ao.bytes.num - sizeof(long);
}
/* ========================================================================== */
/* Encoder packet processing and fragment writer */
static inline int64_t packet_pts_usec(struct encoder_packet *packet)
{
return packet->pts * 1000000 / packet->timebase_den;
}
static inline struct encoder_packet *get_pkt_at(struct deque *dq, size_t idx)
{
return deque_data(dq, idx * sizeof(struct encoder_packet));
}
static inline uint64_t get_longest_track_duration(struct mp4_mux *mux)
{
uint64_t dur = 0;
for (size_t i = 0; i < mux->tracks.num; i++) {
struct mp4_track *track = &mux->tracks.array[i];
uint64_t track_dur = util_mul_div64(track->duration, 1000, track->timebase_den);
if (track_dur > dur)
dur = track_dur;
}
return dur;
}
static void process_packets(struct mp4_mux *mux, struct mp4_track *track, uint64_t *mdat_size)
{
size_t count = track->packets.size / sizeof(struct encoder_packet);
if (!count)
return;
/* Only iterate upt to penultimate packet so we can determine duration
* for all processed packets. */
for (size_t i = 0; i < count - 1; i++) {
struct encoder_packet *pkt = get_pkt_at(&track->packets, i);
if (mux->next_frag_pts && packet_pts_usec(pkt) >= mux->next_frag_pts)
break;
struct encoder_packet *next = get_pkt_at(&track->packets, i + 1);
/* Duration is just distance between current and next DTS. */
uint32_t duration = (uint32_t)(next->dts - pkt->dts);
uint32_t sample_count = 1;
uint32_t size = (uint32_t)pkt->size;
int32_t offset = (int32_t)(pkt->pts - pkt->dts);
/* When using negative CTS, subtract DTS-PTS offset. */
if (track->type == TRACK_VIDEO && mux->flags & MP4_USE_NEGATIVE_CTS) {
if (!track->offsets.num)
track->dts_offset = offset;
offset -= track->dts_offset;
}
/* Create temporary sample information for moof */
struct fragment_sample *smp = da_push_back_new(track->fragment_samples);
smp->size = size;
smp->offset = offset;
smp->duration = duration;
*mdat_size += size;
/* Update global sample information for full moov */
track->duration += duration;
if (track->sample_size) {
/* Adjust duration/count for fixed sample size */
sample_count = size / track->sample_size;
duration = 1;
}
if (!track->samples)
track->first_pts = pkt->pts;
track->samples += sample_count;
/* If delta (duration) matche sprevious, increment counter,
* otherwise create a new entry. */
if (track->deltas.num == 0 || track->deltas.array[track->deltas.num - 1].delta != duration) {
struct sample_delta *new = da_push_back_new(track->deltas);
new->delta = duration;
new->count = sample_count;
} else {
track->deltas.array[track->deltas.num - 1].count += sample_count;
}
if (!track->sample_size)
da_push_back(track->sample_sizes, &size);
if (track->type != TRACK_VIDEO)
continue;
if (pkt->keyframe)
da_push_back(track->sync_samples, &track->samples);
/* Only require ctts box if offet is non-zero */
if (offset && !track->needs_ctts)
track->needs_ctts = true;
/* If dts-pts offset matche sprevious, increment counter,
* otherwise create a new entry. */
if (track->offsets.num == 0 || track->offsets.array[track->offsets.num - 1].offset != offset) {
struct sample_offset *new = da_push_back_new(track->offsets);
new->offset = offset;
new->count = 1;
} else {
track->offsets.array[track->offsets.num - 1].count += 1;
}
}
}
/* Write track data to file */
static void write_packets(struct mp4_mux *mux, struct mp4_track *track)
{
struct serializer *s = mux->serializer;
size_t count = track->packets.size / sizeof(struct encoder_packet);
if (!count || !track->fragment_samples.num)
return;
struct chunk *chk = da_push_back_new(track->chunks);
chk->offset = serializer_get_pos(s);
chk->samples = (uint32_t)track->fragment_samples.num;
for (size_t i = 0; i < track->fragment_samples.num; i++) {
struct encoder_packet pkt;
deque_pop_front(&track->packets, &pkt, sizeof(struct encoder_packet));
s_write(s, pkt.data, pkt.size);
obs_encoder_packet_release(&pkt);
}
chk->size = (uint32_t)(serializer_get_pos(s) - chk->offset);
/* Fixup sample count for fixed-size codecs */
if (track->sample_size)
chk->samples = chk->size / track->sample_size;
da_clear(track->fragment_samples);
}
static void mp4_flush_fragment(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
// Write file header if not already done
if (!mux->fragments_written) {
mp4_write_ftyp(mux, true);
/* Placeholder to write mdat header during soft-remux */
mux->placeholder_offset = serializer_get_pos(s);
mp4_write_free(mux);
}
// Array output as temporary buffer to avoid sending seeks to disk
struct serializer as;
struct array_output_data aod;
array_output_serializer_init(&as, &aod);
mux->serializer = &as;
// Write initial incomplete moov (because fragmentation)
if (!mux->fragments_written) {
mp4_write_moov(mux, true);
s_write(s, aod.bytes.array, aod.bytes.num);
array_output_serializer_reset(&aod);
}
mux->fragments_written++;
/* --------------------------------------------------------- */
/* Analyse packets and create fragment moof. */
uint64_t mdat_size = 8;
for (size_t idx = 0; idx < mux->tracks.num; idx++) {
struct mp4_track *track = &mux->tracks.array[idx];
process_packets(mux, track, &mdat_size);
}
if (!mux->next_frag_pts && mux->chapter_track) {
// Create dummy chapter marker at the end so duration is correct
uint64_t duration = get_longest_track_duration(mux);
struct encoder_packet pkt;
mp4_create_chapter_pkt(&pkt, (int64_t)duration * 1000, "Dummy");
deque_push_back(&mux->chapter_track->packets, &pkt, sizeof(struct encoder_packet));
process_packets(mux, mux->chapter_track, &mdat_size);
}
// write moof once to get size
int64_t moof_start = serializer_get_pos(s);
size_t moof_size = mp4_write_moof(mux, 0, moof_start);
array_output_serializer_reset(&aod);
// write moof again with known size
mp4_write_moof(mux, (uint32_t)moof_size, moof_start);
// Write to output and restore real serializer
s_write(s, aod.bytes.array, aod.bytes.num);
mux->serializer = s;
array_output_serializer_free(&aod);
/* --------------------------------------------------------- */
/* Write audio and video samples (in chunks). Also update */
/* global chunk and sample information for final moov. */
if (mdat_size > UINT32_MAX) {
s_wb32(s, 1);
s_write(s, "mdat", 4);
s_wb64(s, mdat_size + 8);
} else {
s_wb32(s, (uint32_t)mdat_size);
s_write(s, "mdat", 4);
}
for (size_t i = 0; i < mux->tracks.num; i++) {
struct mp4_track *track = &mux->tracks.array[i];
write_packets(mux, track);
}
/* Only write chapter packets on final flush. */
if (!mux->next_frag_pts && mux->chapter_track)
write_packets(mux, mux->chapter_track);
mux->next_frag_pts = 0;
}
/* ========================================================================== */
/* Track object functions */
static inline void track_insert_packet(struct mp4_track *track, struct encoder_packet *pkt)
{
int64_t pts_usec = packet_pts_usec(pkt);
if (pts_usec > track->last_pts_usec)
track->last_pts_usec = pts_usec;
deque_push_back(&track->packets, pkt, sizeof(struct encoder_packet));
}
static inline uint32_t get_sample_size(struct mp4_track *track)
{
audio_t *audio = obs_encoder_audio(track->encoder);
if (!audio)
return 0;
const struct audio_output_info *info = audio_output_get_info(audio);
uint32_t channels = get_audio_channels(info->speakers);
switch (track->codec) {
case CODEC_PCM_F32:
return channels * 4; // 4 bytes per sample (32-bit)
case CODEC_PCM_I24:
return channels * 3; // 3 bytes per sample (24-bit)
case CODEC_PCM_I16:
return channels * 2; // 2 bytes per sample (16-bit)
default:
return 0;
}
}
static inline enum mp4_codec get_codec(obs_encoder_t *enc)
{
const char *codec = obs_encoder_get_codec(enc);
if (strcmp(codec, "h264") == 0)
return CODEC_H264;
if (strcmp(codec, "hevc") == 0)
return CODEC_HEVC;
if (strcmp(codec, "av1") == 0)
return CODEC_AV1;
if (strcmp(codec, "aac") == 0)
return CODEC_AAC;
if (strcmp(codec, "opus") == 0)
return CODEC_OPUS;
if (strcmp(codec, "flac") == 0)
return CODEC_FLAC;
if (strcmp(codec, "alac") == 0)
return CODEC_ALAC;
if (strcmp(codec, "pcm_s16le") == 0)
return CODEC_PCM_I16;
if (strcmp(codec, "pcm_s24le") == 0)
return CODEC_PCM_I24;
if (strcmp(codec, "pcm_f32le") == 0)
return CODEC_PCM_F32;
return CODEC_UNKNOWN;
}
static inline void add_track(struct mp4_mux *mux, obs_encoder_t *enc)
{
struct mp4_track *track = da_push_back_new(mux->tracks);
track->type = obs_encoder_get_type(enc) == OBS_ENCODER_VIDEO ? TRACK_VIDEO : TRACK_AUDIO;
track->encoder = obs_encoder_get_ref(enc);
track->codec = get_codec(enc);
track->track_id = ++mux->track_ctr;
/* Set timebase/timescale */
if (track->type == TRACK_VIDEO) {
video_t *video = obs_encoder_video(enc);
const struct video_output_info *info = video_output_get_info(video);
track->timebase_num = info->fps_den;
track->timebase_den = info->fps_num;
track->timescale = track->timebase_den;
/* FFmpeg does this to compensate for non-monotonic timestamps,
* we probably don't need it, but let's stick to what they do
* for maximum compatibility. */
while (track->timescale < 10000)
track->timescale *= 2;
} else {
uint32_t sample_rate = obs_encoder_get_sample_rate(enc);
/* Opus is always 48 kHz */
if (track->codec == CODEC_OPUS)
sample_rate = 48000;
track->timebase_num = 1;
track->timebase_den = sample_rate;
track->timescale = sample_rate;
}
/* Set sample size (if fixed) */
if (track->type == TRACK_AUDIO)
track->sample_size = get_sample_size(track);
}
static inline void add_chapter_track(struct mp4_mux *mux)
{
mux->chapter_track = bzalloc(sizeof(struct mp4_track));
mux->chapter_track->type = TRACK_CHAPTERS;
mux->chapter_track->codec = CODEC_TEXT;
mux->chapter_track->timescale = 1000;
mux->chapter_track->timebase_num = 1;
mux->chapter_track->timebase_den = 1000;
mux->chapter_track->track_id = ++mux->track_ctr;
}
static inline void free_packets(struct deque *dq)
{
size_t num = dq->size / sizeof(struct encoder_packet);
for (size_t i = 0; i < num; i++) {
struct encoder_packet pkt;
deque_pop_front(dq, &pkt, sizeof(struct encoder_packet));
obs_encoder_packet_release(&pkt);
}
}
static inline void free_track(struct mp4_track *track)
{
if (!track)
return;
obs_encoder_release(track->encoder);
free_packets(&track->packets);
deque_free(&track->packets);
da_free(track->sample_sizes);
da_free(track->chunks);
da_free(track->deltas);
da_free(track->offsets);
da_free(track->sync_samples);
da_free(track->fragment_samples);
}
/* ===========================================================================*/
/* API */
struct mp4_mux *mp4_mux_create(obs_output_t *output, struct serializer *serializer, enum mp4_mux_flags flags)
{
struct mp4_mux *mux = bzalloc(sizeof(struct mp4_mux));
mux->output = output;
mux->serializer = serializer;
mux->flags = flags;
/* Timestamp is based on 1904 rather than 1970. */
mux->creation_time = time(NULL) + 0x7C25B080;
for (size_t i = 0; i < MAX_OUTPUT_VIDEO_ENCODERS; i++) {
obs_encoder_t *enc = obs_output_get_video_encoder2(output, i);
if (!enc)
continue;
add_track(mux, enc);
}
for (size_t i = 0; i < MAX_OUTPUT_AUDIO_ENCODERS; i++) {
obs_encoder_t *enc = obs_output_get_audio_encoder(output, i);
if (!enc)
continue;
add_track(mux, enc);
}
return mux;
}
void mp4_mux_destroy(struct mp4_mux *mux)
{
for (size_t i = 0; i < mux->tracks.num; i++)
free_track(&mux->tracks.array[i]);
free_track(mux->chapter_track);
bfree(mux->chapter_track);
da_free(mux->tracks);
bfree(mux);
}
bool mp4_mux_submit_packet(struct mp4_mux *mux, struct encoder_packet *pkt)
{
struct mp4_track *track = NULL;
struct encoder_packet parsed_packet;
enum obs_encoder_type type = pkt->type;
bool fragment_ready = mux->next_frag_pts > 0;
for (size_t i = 0; i < mux->tracks.num; i++) {
struct mp4_track *tmp = &mux->tracks.array[i];
fragment_ready = fragment_ready && tmp->last_pts_usec >= mux->next_frag_pts;
if (tmp->encoder == pkt->encoder)
track = tmp;
}
if (!track) {
warn("Could not find track for packet of type %s with "
"track id %zu!",
type == OBS_ENCODER_VIDEO ? "video" : "audio", pkt->track_idx);
return false;
}
/* If all tracks have caught up to the keyframe we want to fragment on,
* flush the current fragment to disk. */
if (fragment_ready)
mp4_flush_fragment(mux);
if (type == OBS_ENCODER_AUDIO) {
obs_encoder_packet_ref(&parsed_packet, pkt);
} else {
if (track->codec == CODEC_H264)
obs_parse_avc_packet(&parsed_packet, pkt);
else if (track->codec == CODEC_HEVC)
obs_parse_hevc_packet(&parsed_packet, pkt);
else if (track->codec == CODEC_AV1)
obs_parse_av1_packet(&parsed_packet, pkt);
/* Set fragmentation PTS if packet is keyframe and PTS > 0 */
if (parsed_packet.keyframe && parsed_packet.pts > 0) {
mux->next_frag_pts = packet_pts_usec(&parsed_packet);
}
}
track_insert_packet(track, &parsed_packet);
return true;
}
bool mp4_mux_add_chapter(struct mp4_mux *mux, int64_t dts_usec, const char *name)
{
if (dts_usec < 0)
return false;
if (!mux->chapter_track)
add_chapter_track(mux);
/* To work correctly there needs to be a chapter at PTS 0,
* create that here if necessary. */
if (dts_usec > 0 && mux->chapter_track->packets.size == 0) {
mp4_mux_add_chapter(mux, 0, obs_module_text("MP4Output.StartChapter"));
}
/* Create packets that will be muxed on final flush */
struct encoder_packet pkt;
mp4_create_chapter_pkt(&pkt, dts_usec, name);
track_insert_packet(mux->chapter_track, &pkt);
return true;
}
bool mp4_mux_finalise(struct mp4_mux *mux)
{
struct serializer *s = mux->serializer;
/* Flush remaining audio/video samples as final fragment. */
info("Flushing final fragment...");
/* Set target PTS to zero to indicate that we want to flush all
* the remaining packets */
mux->next_frag_pts = 0;
mp4_flush_fragment(mux);
info("Number of fragments: %u", mux->fragments_written);
if (mux->flags & MP4_SKIP_FINALISATION) {
warn("Skipping MP4 finalization!");
return true;
}
int64_t data_end = serializer_get_pos(s);
/* ---------------------------------------- */
/* Write full moov box */
/* Use array serializer for moov data as this will do a lot
* of seeks to write size values of variable-size boxes. */
struct serializer fs;
struct array_output_data ao;
array_output_serializer_init(&fs, &ao);
mux->serializer = &fs;
mp4_write_moov(mux, false);
s_write(s, ao.bytes.array, ao.bytes.num);
info("Full moov size: %zu KiB", ao.bytes.num / 1024);
mux->serializer = s; // restore real serializer
array_output_serializer_free(&ao);
/* ---------------------------------------- */
/* Overwrite file header (ftyp + free/moov) */
serializer_seek(s, 0, SERIALIZE_SEEK_START);
mp4_write_ftyp(mux, false);
size_t data_size = data_end - mux->placeholder_offset;
serializer_seek(s, (int64_t)mux->placeholder_offset, SERIALIZE_SEEK_START);
/* If data is more than 4 GiB the mdat header becomes 16 bytes, hence
* why we create a 16-byte placeholder "free" box at the start. */
if (data_size > UINT32_MAX) {
s_wb32(s, 1); // 1 = use "largesize" field instead
s_write(s, "mdat", 4);
s_wb64(s, data_size); // largesize (64-bit)
} else {
s_wb32(s, (uint32_t)data_size);
s_write(s, "mdat", 4);
}
info("Final mdat size: %zu KiB", data_size / 1024);
return true;
}
| 73,412 |
C
|
.c
| 2,094 | 32.616046 | 114 | 0.670691 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,510 |
flv-mux.c
|
obsproject_obs-studio/plugins/obs-outputs/flv-mux.c
|
/******************************************************************************
Copyright (C) 2023 by Lain Bailey <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include <obs.h>
#include <stdio.h>
#include <util/dstr.h>
#include <util/array-serializer.h>
#include "flv-mux.h"
#include "obs-output-ver.h"
#include "rtmp-helpers.h"
/* TODO: FIXME: this is currently hard-coded to h264 and aac! ..not that we'll
* use anything else for a long time. */
//#define DEBUG_TIMESTAMPS
//#define WRITE_FLV_HEADER
#define AUDIODATA_AAC 10.0
#define AUDIO_FRAMETYPE_OFFSET 4
#define VIDEO_FRAMETYPE_OFFSET 4
enum video_frametype_t {
FT_KEY = 1 << VIDEO_FRAMETYPE_OFFSET,
FT_INTER = 2 << VIDEO_FRAMETYPE_OFFSET,
};
// Y2023 spec
const uint8_t AUDIO_HEADER_EX = 9 << AUDIO_FRAMETYPE_OFFSET;
enum audio_packet_type_t {
AUDIO_PACKETTYPE_SEQ_START = 0,
AUDIO_PACKETTYPE_FRAMES = 1,
AUDIO_PACKETTYPE_MULTICHANNEL_CONFIG = 4,
AUDIO_PACKETTYPE_MULTITRACK = 5,
};
const uint8_t FRAME_HEADER_EX = 8 << VIDEO_FRAMETYPE_OFFSET;
enum packet_type_t {
PACKETTYPE_SEQ_START = 0,
PACKETTYPE_FRAMES = 1,
PACKETTYPE_SEQ_END = 2,
PACKETTYPE_FRAMESX = 3,
PACKETTYPE_METADATA = 4,
PACKETTYPE_MPEG2TS_SEQ_START = 5,
PACKETTYPE_MULTITRACK = 6
};
enum multitrack_type_t {
MULTITRACKTYPE_ONE_TRACK = 0x00,
MULTITRACKTYPE_MANY_TRACKS = 0x10,
MULTITRACKTYPE_MANY_TRACKS_MANY_CODECS = 0x20,
};
enum datatype_t {
DATA_TYPE_NUMBER = 0,
DATA_TYPE_STRING = 2,
DATA_TYPE_OBJECT = 3,
DATA_TYPE_OBJECT_END = 9,
};
static void s_wa4cc(struct serializer *s, enum audio_id_t id)
{
switch (id) {
case AUDIO_CODEC_NONE:
assert(0 && "Tried to serialize AUDIO_CODEC_NONE");
break;
case AUDIO_CODEC_AAC:
s_w8(s, 'm');
s_w8(s, 'p');
s_w8(s, '4');
s_w8(s, 'a');
break;
}
}
static void s_w4cc(struct serializer *s, enum video_id_t id)
{
switch (id) {
case CODEC_NONE:
assert(0 && "Tried to serialize CODEC_NONE");
break;
case CODEC_AV1:
s_w8(s, 'a');
s_w8(s, 'v');
s_w8(s, '0');
s_w8(s, '1');
break;
case CODEC_HEVC:
#ifdef ENABLE_HEVC
s_w8(s, 'h');
s_w8(s, 'v');
s_w8(s, 'c');
s_w8(s, '1');
break;
#else
assert(0);
#endif
case CODEC_H264:
s_w8(s, 'a');
s_w8(s, 'v');
s_w8(s, 'c');
s_w8(s, '1');
break;
}
}
static void s_wstring(struct serializer *s, const char *str)
{
size_t len = strlen(str);
s_wb16(s, (uint16_t)len);
s_write(s, str, len);
}
static inline void s_wtimestamp(struct serializer *s, int32_t i32)
{
s_wb24(s, (uint32_t)(i32 & 0xFFFFFF));
s_w8(s, (uint32_t)(i32 >> 24) & 0x7F);
}
static inline double encoder_bitrate(obs_encoder_t *encoder)
{
obs_data_t *settings = obs_encoder_get_settings(encoder);
double bitrate = obs_data_get_double(settings, "bitrate");
obs_data_release(settings);
return bitrate;
}
static const double VIDEODATA_AVCVIDEOPACKET = 7.0;
// Additional FLV onMetaData values for Enhanced RTMP/FLV
static const double VIDEODATA_AV1VIDEOPACKET = 1635135537.0; // FourCC "av01"
#ifdef ENABLE_HEVC
static const double VIDEODATA_HEVCVIDEOPACKET = 1752589105.0; // FourCC "hvc1"
#endif
static inline double encoder_video_codec(obs_encoder_t *encoder)
{
const char *codec = obs_encoder_get_codec(encoder);
if (strcmp(codec, "h264") == 0)
return VIDEODATA_AVCVIDEOPACKET;
if (strcmp(codec, "av1") == 0)
return VIDEODATA_AV1VIDEOPACKET;
#ifdef ENABLE_HEVC
if (strcmp(codec, "hevc") == 0)
return VIDEODATA_HEVCVIDEOPACKET;
#endif
return 0.0;
}
/*
* This is based on the position of `duration` and `fileSize` in
* `build_flv_meta_data` relative to the beginning of the file
* to allow `write_file_info` to overwrite these two fields once
* the file is finalized.
*/
#define FLV_INFO_SIZE_OFFSET 58
void write_file_info(FILE *file, int64_t duration_ms, int64_t size)
{
char buf[64];
char *enc = buf;
char *end = enc + sizeof(buf);
fseek(file, FLV_INFO_SIZE_OFFSET, SEEK_SET);
enc_num_val(&enc, end, "duration", (double)duration_ms / 1000.0);
enc_num_val(&enc, end, "fileSize", (double)size);
fwrite(buf, 1, enc - buf, file);
}
static void build_flv_meta_data(obs_output_t *context, uint8_t **output, size_t *size)
{
obs_encoder_t *vencoder = obs_output_get_video_encoder(context);
obs_encoder_t *aencoder = obs_output_get_audio_encoder(context, 0);
video_t *video = obs_encoder_video(vencoder);
audio_t *audio = obs_encoder_audio(aencoder);
char buf[4096];
char *enc = buf;
char *end = enc + sizeof(buf);
struct dstr encoder_name = {0};
enc_str(&enc, end, "@setDataFrame");
enc_str(&enc, end, "onMetaData");
*enc++ = AMF_ECMA_ARRAY;
enc = AMF_EncodeInt32(enc, end, 20);
enc_num_val(&enc, end, "duration", 0.0);
enc_num_val(&enc, end, "fileSize", 0.0);
enc_num_val(&enc, end, "width", (double)obs_encoder_get_width(vencoder));
enc_num_val(&enc, end, "height", (double)obs_encoder_get_height(vencoder));
enc_num_val(&enc, end, "videocodecid", encoder_video_codec(vencoder));
enc_num_val(&enc, end, "videodatarate", encoder_bitrate(vencoder));
enc_num_val(&enc, end, "framerate", video_output_get_frame_rate(video));
enc_num_val(&enc, end, "audiocodecid", AUDIODATA_AAC);
enc_num_val(&enc, end, "audiodatarate", encoder_bitrate(aencoder));
enc_num_val(&enc, end, "audiosamplerate", (double)obs_encoder_get_sample_rate(aencoder));
enc_num_val(&enc, end, "audiosamplesize", 16.0);
enc_num_val(&enc, end, "audiochannels", (double)audio_output_get_channels(audio));
enc_bool_val(&enc, end, "stereo", audio_output_get_channels(audio) == 2);
enc_bool_val(&enc, end, "2.1", audio_output_get_channels(audio) == 3);
enc_bool_val(&enc, end, "3.1", audio_output_get_channels(audio) == 4);
enc_bool_val(&enc, end, "4.0", audio_output_get_channels(audio) == 4);
enc_bool_val(&enc, end, "4.1", audio_output_get_channels(audio) == 5);
enc_bool_val(&enc, end, "5.1", audio_output_get_channels(audio) == 6);
enc_bool_val(&enc, end, "7.1", audio_output_get_channels(audio) == 8);
dstr_printf(&encoder_name, "%s (libobs version ", MODULE_NAME);
#ifdef HAVE_OBSCONFIG_H
dstr_cat(&encoder_name, obs_get_version_string());
#else
dstr_catf(&encoder_name, "%d.%d.%d", LIBOBS_API_MAJOR_VER, LIBOBS_API_MINOR_VER, LIBOBS_API_PATCH_VER);
#endif
dstr_cat(&encoder_name, ")");
enc_str_val(&enc, end, "encoder", encoder_name.array);
dstr_free(&encoder_name);
*enc++ = 0;
*enc++ = 0;
*enc++ = AMF_OBJECT_END;
*size = enc - buf;
*output = bmemdup(buf, *size);
}
static inline void write_previous_tag_size_without_header(struct serializer *s, uint32_t header_size)
{
assert(serializer_get_pos(s) >= header_size);
assert(serializer_get_pos(s) >= 11);
/*
* From FLV file format specification version 10:
* Size of previous [current] tag, including its header.
* For FLV version 1 this value is 11 plus the DataSize of
* the previous [current] tag.
*/
s_wb32(s, (uint32_t)serializer_get_pos(s) - header_size);
}
static inline void write_previous_tag_size(struct serializer *s)
{
write_previous_tag_size_without_header(s, 0);
}
void flv_meta_data(obs_output_t *context, uint8_t **output, size_t *size, bool write_header)
{
struct array_output_data data;
struct serializer s;
uint8_t *meta_data = NULL;
size_t meta_data_size;
uint32_t start_pos;
array_output_serializer_init(&s, &data);
build_flv_meta_data(context, &meta_data, &meta_data_size);
if (write_header) {
s_write(&s, "FLV", 3);
s_w8(&s, 1);
s_w8(&s, 5);
s_wb32(&s, 9);
s_wb32(&s, 0);
}
start_pos = serializer_get_pos(&s);
s_w8(&s, RTMP_PACKET_TYPE_INFO);
s_wb24(&s, (uint32_t)meta_data_size);
s_wb32(&s, 0);
s_wb24(&s, 0);
s_write(&s, meta_data, meta_data_size);
write_previous_tag_size_without_header(&s, start_pos);
*output = data.bytes.array;
*size = data.bytes.num;
bfree(meta_data);
}
#ifdef DEBUG_TIMESTAMPS
static int32_t last_time = 0;
#endif
static void flv_video(struct serializer *s, int32_t dts_offset, struct encoder_packet *packet, bool is_header)
{
int64_t offset = packet->pts - packet->dts;
int32_t time_ms = get_ms_time(packet, packet->dts) - dts_offset;
if (!packet->data || !packet->size)
return;
s_w8(s, RTMP_PACKET_TYPE_VIDEO);
#ifdef DEBUG_TIMESTAMPS
blog(LOG_DEBUG, "Video: %lu", time_ms);
if (last_time > time_ms)
blog(LOG_DEBUG, "Non-monotonic");
last_time = time_ms;
#endif
s_wb24(s, (uint32_t)packet->size + 5);
s_wb24(s, (uint32_t)time_ms);
s_w8(s, (time_ms >> 24) & 0x7F);
s_wb24(s, 0);
/* these are the 5 extra bytes mentioned above */
s_w8(s, packet->keyframe ? 0x17 : 0x27);
s_w8(s, is_header ? 0 : 1);
s_wb24(s, get_ms_time(packet, offset));
s_write(s, packet->data, packet->size);
write_previous_tag_size(s);
}
static void flv_audio(struct serializer *s, int32_t dts_offset, struct encoder_packet *packet, bool is_header)
{
int32_t time_ms = get_ms_time(packet, packet->dts) - dts_offset;
if (!packet->data || !packet->size)
return;
s_w8(s, RTMP_PACKET_TYPE_AUDIO);
#ifdef DEBUG_TIMESTAMPS
blog(LOG_DEBUG, "Audio: %lu", time_ms);
if (last_time > time_ms)
blog(LOG_DEBUG, "Non-monotonic");
last_time = time_ms;
#endif
s_wb24(s, (uint32_t)packet->size + 2);
s_wb24(s, (uint32_t)time_ms);
s_w8(s, (time_ms >> 24) & 0x7F);
s_wb24(s, 0);
/* these are the two extra bytes mentioned above */
s_w8(s, 0xaf);
s_w8(s, is_header ? 0 : 1);
s_write(s, packet->data, packet->size);
write_previous_tag_size(s);
}
void flv_packet_mux(struct encoder_packet *packet, int32_t dts_offset, uint8_t **output, size_t *size, bool is_header)
{
struct array_output_data data;
struct serializer s;
array_output_serializer_init(&s, &data);
if (packet->type == OBS_ENCODER_VIDEO)
flv_video(&s, dts_offset, packet, is_header);
else
flv_audio(&s, dts_offset, packet, is_header);
*output = data.bytes.array;
*size = data.bytes.num;
}
void flv_packet_audio_ex(struct encoder_packet *packet, enum audio_id_t codec_id, int32_t dts_offset, uint8_t **output,
size_t *size, int type, size_t idx)
{
struct array_output_data data;
struct serializer s;
array_output_serializer_init(&s, &data);
assert(packet->type == OBS_ENCODER_AUDIO);
int32_t time_ms = get_ms_time(packet, packet->dts) - dts_offset;
bool is_multitrack = idx > 0;
if (!packet->data || !packet->size)
return;
int header_metadata_size = 5; // w8+wa4cc
if (is_multitrack)
header_metadata_size += 2; // w8 + w8
s_w8(&s, RTMP_PACKET_TYPE_AUDIO);
#ifdef DEBUG_TIMESTAMPS
blog(LOG_DEBUG, "Audio: %lu", time_ms);
if (last_time > time_ms)
blog(LOG_DEBUG, "Non-monotonic");
last_time = time_ms;
#endif
s_wb24(&s, (uint32_t)packet->size + header_metadata_size);
s_wb24(&s, (uint32_t)time_ms);
s_w8(&s, (time_ms >> 24) & 0x7F);
s_wb24(&s, 0);
s_w8(&s, AUDIO_HEADER_EX | (is_multitrack ? AUDIO_PACKETTYPE_MULTITRACK : type));
if (is_multitrack) {
s_w8(&s, MULTITRACKTYPE_ONE_TRACK | type);
s_wa4cc(&s, codec_id);
s_w8(&s, (uint8_t)idx);
} else {
s_wa4cc(&s, codec_id);
}
s_write(&s, packet->data, packet->size);
write_previous_tag_size(&s);
*output = data.bytes.array;
*size = data.bytes.num;
}
// Y2023 spec
void flv_packet_ex(struct encoder_packet *packet, enum video_id_t codec_id, int32_t dts_offset, uint8_t **output,
size_t *size, int type, size_t idx)
{
struct array_output_data data;
struct serializer s;
array_output_serializer_init(&s, &data);
assert(packet->type == OBS_ENCODER_VIDEO);
int32_t time_ms = get_ms_time(packet, packet->dts) - dts_offset;
bool is_multitrack = idx > 0;
// packet head
int header_metadata_size = 5; // w8+w4cc
// 3 extra bytes for composition time offset
if ((codec_id == CODEC_H264 || codec_id == CODEC_HEVC) && type == PACKETTYPE_FRAMES) {
header_metadata_size += 3; // w24
}
if (is_multitrack)
header_metadata_size += 2; // w8+w8
s_w8(&s, RTMP_PACKET_TYPE_VIDEO);
s_wb24(&s, (uint32_t)packet->size + header_metadata_size);
s_wtimestamp(&s, time_ms);
s_wb24(&s, 0); // always 0
uint8_t frame_type = packet->keyframe ? FT_KEY : FT_INTER;
/*
* We only explicitly emit trackIds iff idx > 0.
* The default trackId is 0.
*/
if (is_multitrack) {
s_w8(&s, FRAME_HEADER_EX | PACKETTYPE_MULTITRACK | frame_type);
s_w8(&s, MULTITRACKTYPE_ONE_TRACK | type);
s_w4cc(&s, codec_id);
// trackId
s_w8(&s, (uint8_t)idx);
} else {
s_w8(&s, FRAME_HEADER_EX | type | frame_type);
s_w4cc(&s, codec_id);
}
// H.264/HEVC composition time offset
if ((codec_id == CODEC_H264 || codec_id == CODEC_HEVC) && type == PACKETTYPE_FRAMES) {
s_wb24(&s, get_ms_time(packet, packet->pts - packet->dts));
}
// packet data
s_write(&s, packet->data, packet->size);
// packet tail
write_previous_tag_size(&s);
*output = data.bytes.array;
*size = data.bytes.num;
}
void flv_packet_start(struct encoder_packet *packet, enum video_id_t codec, uint8_t **output, size_t *size, size_t idx)
{
flv_packet_ex(packet, codec, 0, output, size, PACKETTYPE_SEQ_START, idx);
}
void flv_packet_frames(struct encoder_packet *packet, enum video_id_t codec, int32_t dts_offset, uint8_t **output,
size_t *size, size_t idx)
{
int packet_type = PACKETTYPE_FRAMES;
// PACKETTYPE_FRAMESX is an optimization to avoid sending composition
// time offsets of 0. See Enhanced RTMP spec.
if ((codec == CODEC_H264 || codec == CODEC_HEVC) && packet->dts == packet->pts)
packet_type = PACKETTYPE_FRAMESX;
flv_packet_ex(packet, codec, dts_offset, output, size, packet_type, idx);
}
void flv_packet_end(struct encoder_packet *packet, enum video_id_t codec, uint8_t **output, size_t *size, size_t idx)
{
flv_packet_ex(packet, codec, 0, output, size, PACKETTYPE_SEQ_END, idx);
}
void flv_packet_audio_start(struct encoder_packet *packet, enum audio_id_t codec, uint8_t **output, size_t *size,
size_t idx)
{
flv_packet_audio_ex(packet, codec, 0, output, size, AUDIO_PACKETTYPE_SEQ_START, idx);
}
void flv_packet_audio_frames(struct encoder_packet *packet, enum audio_id_t codec, int32_t dts_offset, uint8_t **output,
size_t *size, size_t idx)
{
flv_packet_audio_ex(packet, codec, dts_offset, output, size, AUDIO_PACKETTYPE_FRAMES, idx);
}
void flv_packet_metadata(enum video_id_t codec_id, uint8_t **output, size_t *size, int bits_per_raw_sample,
uint8_t color_primaries, int color_trc, int color_space, int min_luminance, int max_luminance,
size_t idx)
{
// metadata array
struct array_output_data data;
struct array_output_data metadata;
struct serializer s;
array_output_serializer_init(&s, &data);
// metadata data array
{
struct serializer s;
array_output_serializer_init(&s, &metadata);
s_w8(&s, DATA_TYPE_STRING);
s_wstring(&s, "colorInfo");
s_w8(&s, DATA_TYPE_OBJECT);
{
// colorConfig:
s_wstring(&s, "colorConfig");
s_w8(&s, DATA_TYPE_OBJECT);
{
s_wstring(&s, "bitDepth");
s_w8(&s, DATA_TYPE_NUMBER);
s_wbd(&s, bits_per_raw_sample);
s_wstring(&s, "colorPrimaries");
s_w8(&s, DATA_TYPE_NUMBER);
s_wbd(&s, color_primaries);
s_wstring(&s, "transferCharacteristics");
s_w8(&s, DATA_TYPE_NUMBER);
s_wbd(&s, color_trc);
s_wstring(&s, "matrixCoefficients");
s_w8(&s, DATA_TYPE_NUMBER);
s_wbd(&s, color_space);
}
s_w8(&s, 0);
s_w8(&s, 0);
s_w8(&s, DATA_TYPE_OBJECT_END);
if (max_luminance != 0) {
// hdrMdcv
s_wstring(&s, "hdrMdcv");
s_w8(&s, DATA_TYPE_OBJECT);
{
s_wstring(&s, "maxLuminance");
s_w8(&s, DATA_TYPE_NUMBER);
s_wbd(&s, max_luminance);
s_wstring(&s, "minLuminance");
s_w8(&s, DATA_TYPE_NUMBER);
s_wbd(&s, min_luminance);
}
s_w8(&s, 0);
s_w8(&s, 0);
s_w8(&s, DATA_TYPE_OBJECT_END);
}
}
s_w8(&s, 0);
s_w8(&s, 0);
s_w8(&s, DATA_TYPE_OBJECT_END);
}
bool is_multitrack = idx > 0;
// packet head
// w8+w4cc
int header_metadata_size = 5;
if (is_multitrack) {
// w8+w8
header_metadata_size += 2;
}
s_w8(&s, RTMP_PACKET_TYPE_VIDEO);
s_wb24(&s, (uint32_t)metadata.bytes.num + header_metadata_size);
s_wtimestamp(&s, 0);
s_wb24(&s, 0); // always 0
// packet ext header
// these are the 5 extra bytes mentioned above
s_w8(&s, FRAME_HEADER_EX | (is_multitrack ? PACKETTYPE_MULTITRACK : PACKETTYPE_METADATA));
/*
* We only add explicitly emit trackIds iff idx > 0.
* The default trackId is 0.
*/
if (is_multitrack) {
s_w8(&s, (uint8_t)MULTITRACKTYPE_ONE_TRACK | (uint8_t)PACKETTYPE_METADATA);
s_w4cc(&s, codec_id);
// trackId
s_w8(&s, (uint8_t)idx);
} else {
s_w4cc(&s, codec_id);
}
// packet data
s_write(&s, metadata.bytes.array, metadata.bytes.num);
array_output_serializer_free(&metadata); // must be freed
// packet tail
write_previous_tag_size(&s);
*output = data.bytes.array;
*size = data.bytes.num;
}
| 17,352 |
C
|
.c
| 517 | 31.05029 | 120 | 0.683108 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,511 |
mp4-output.c
|
obsproject_obs-studio/plugins/obs-outputs/mp4-output.c
|
/******************************************************************************
Copyright (C) 2024 by Dennis Sädtler <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include "mp4-mux.h"
#include <inttypes.h>
#include <obs-module.h>
#include <util/platform.h>
#include <util/dstr.h>
#include <util/threading.h>
#include <util/buffered-file-serializer.h>
#include <opts-parser.h>
#define do_log(level, format, ...) \
blog(level, "[mp4 output: '%s'] " format, obs_output_get_name(out->output), ##__VA_ARGS__)
#define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
#define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
struct chapter {
int64_t dts_usec;
char *name;
};
struct mp4_output {
obs_output_t *output;
struct dstr path;
struct serializer serializer;
volatile bool active;
volatile bool stopping;
uint64_t stop_ts;
bool allow_overwrite;
uint64_t total_bytes;
pthread_mutex_t mutex;
struct mp4_mux *muxer;
int flags;
int64_t last_dts_usec;
DARRAY(struct chapter) chapters;
/* File splitting stuff */
bool split_file_enabled;
bool split_file_ready;
volatile bool manual_split;
size_t cur_size;
size_t max_size;
int64_t start_time;
int64_t max_time;
bool found_video[MAX_OUTPUT_VIDEO_ENCODERS];
bool found_audio[MAX_OUTPUT_AUDIO_ENCODERS];
int64_t video_pts_offsets[MAX_OUTPUT_VIDEO_ENCODERS];
int64_t audio_dts_offsets[MAX_OUTPUT_AUDIO_ENCODERS];
/* Buffer for packets while we reinitialise the muxer after splitting */
DARRAY(struct encoder_packet) split_buffer;
};
static inline bool stopping(struct mp4_output *out)
{
return os_atomic_load_bool(&out->stopping);
}
static inline bool active(struct mp4_output *out)
{
return os_atomic_load_bool(&out->active);
}
static inline int64_t packet_pts_usec(struct encoder_packet *packet)
{
return packet->pts * 1000000 / packet->timebase_den;
}
static inline void ts_offset_clear(struct mp4_output *out)
{
for (size_t i = 0; i < MAX_OUTPUT_VIDEO_ENCODERS; i++) {
out->found_video[i] = false;
out->video_pts_offsets[i] = 0;
}
for (size_t i = 0; i < MAX_OUTPUT_AUDIO_ENCODERS; i++) {
out->found_audio[i] = false;
out->audio_dts_offsets[i] = 0;
}
}
static inline void ts_offset_update(struct mp4_output *out, struct encoder_packet *packet)
{
int64_t *offset;
int64_t ts;
bool *found;
if (packet->type == OBS_ENCODER_VIDEO) {
offset = &out->video_pts_offsets[packet->track_idx];
found = &out->found_video[packet->track_idx];
ts = packet->pts;
} else {
offset = &out->audio_dts_offsets[packet->track_idx];
found = &out->found_audio[packet->track_idx];
ts = packet->dts;
}
if (*found)
return;
*offset = ts;
*found = true;
}
static const char *mp4_output_name(void *unused)
{
UNUSED_PARAMETER(unused);
return obs_module_text("MP4Output");
}
static void mp4_output_destory(void *data)
{
struct mp4_output *out = data;
for (size_t i = 0; i < out->chapters.num; i++)
bfree(out->chapters.array[i].name);
da_free(out->chapters);
pthread_mutex_destroy(&out->mutex);
dstr_free(&out->path);
bfree(out);
}
static void mp4_add_chapter_proc(void *data, calldata_t *cd)
{
struct mp4_output *out = data;
struct dstr name = {0};
dstr_copy(&name, calldata_string(cd, "chapter_name"));
if (name.len == 0) {
/* Generate name if none provided. */
dstr_catf(&name, "%s %zu", obs_module_text("MP4Output.UnnamedChapter"), out->chapters.num + 1);
}
int64_t totalRecordSeconds = out->last_dts_usec / 1000 / 1000;
int seconds = (int)totalRecordSeconds % 60;
int totalMinutes = (int)totalRecordSeconds / 60;
int minutes = totalMinutes % 60;
int hours = totalMinutes / 60;
info("Adding chapter \"%s\" at %02d:%02d:%02d", name.array, hours, minutes, seconds);
pthread_mutex_lock(&out->mutex);
struct chapter *chap = da_push_back_new(out->chapters);
chap->dts_usec = out->last_dts_usec;
chap->name = name.array;
pthread_mutex_unlock(&out->mutex);
}
static void split_file_proc(void *data, calldata_t *cd)
{
struct mp4_output *out = data;
calldata_set_bool(cd, "split_file_enabled", out->split_file_enabled);
if (!out->split_file_enabled)
return;
os_atomic_set_bool(&out->manual_split, true);
}
static void *mp4_output_create(obs_data_t *settings, obs_output_t *output)
{
struct mp4_output *out = bzalloc(sizeof(struct mp4_output));
out->output = output;
pthread_mutex_init(&out->mutex, NULL);
signal_handler_t *sh = obs_output_get_signal_handler(output);
signal_handler_add(sh, "void file_changed(string next_file)");
proc_handler_t *ph = obs_output_get_proc_handler(output);
proc_handler_add(ph, "void split_file(out bool split_file_enabled)", split_file_proc, out);
proc_handler_add(ph, "void add_chapter(string chapter_name)", mp4_add_chapter_proc, out);
UNUSED_PARAMETER(settings);
return out;
}
static inline void apply_flag(int *flags, const char *value, int flag_value)
{
if (atoi(value))
*flags |= flag_value;
else
*flags &= ~flag_value;
}
static int parse_custom_options(const char *opts_str)
{
int flags = MP4_USE_NEGATIVE_CTS;
struct obs_options opts = obs_parse_options(opts_str);
for (size_t i = 0; i < opts.count; i++) {
struct obs_option opt = opts.options[i];
if (strcmp(opt.name, "skip_soft_remux") == 0) {
apply_flag(&flags, opt.value, MP4_SKIP_FINALISATION);
} else if (strcmp(opt.name, "write_encoder_info") == 0) {
apply_flag(&flags, opt.value, MP4_WRITE_ENCODER_INFO);
} else if (strcmp(opt.name, "use_metadata_tags") == 0) {
apply_flag(&flags, opt.value, MP4_USE_MDTA_KEY_VALUE);
} else if (strcmp(opt.name, "use_negative_cts") == 0) {
apply_flag(&flags, opt.value, MP4_USE_NEGATIVE_CTS);
} else {
blog(LOG_WARNING, "Unknown muxer option: %s = %s", opt.name, opt.value);
}
}
obs_free_options(opts);
return flags;
}
static bool mp4_output_start(void *data)
{
struct mp4_output *out = data;
if (!obs_output_can_begin_data_capture(out->output, 0))
return false;
if (!obs_output_initialize_encoders(out->output, 0))
return false;
os_atomic_set_bool(&out->stopping, false);
/* get path */
obs_data_t *settings = obs_output_get_settings(out->output);
const char *path = obs_data_get_string(settings, "path");
dstr_copy(&out->path, path);
out->max_time = obs_data_get_int(settings, "max_time_sec") * 1000000LL;
out->max_size = obs_data_get_int(settings, "max_size_mb") * 1024 * 1024;
out->split_file_enabled = obs_data_get_bool(settings, "split_file");
out->allow_overwrite = obs_data_get_bool(settings, "allow_overwrite");
out->cur_size = 0;
/* Allow skipping the remux step for debugging purposes. */
const char *muxer_settings = obs_data_get_string(settings, "muxer_settings");
out->flags = parse_custom_options(muxer_settings);
obs_data_release(settings);
if (!buffered_file_serializer_init_defaults(&out->serializer, out->path.array)) {
warn("Unable to open MP4 file '%s'", out->path.array);
return false;
}
/* Initialise muxer and start capture */
out->muxer = mp4_mux_create(out->output, &out->serializer, out->flags);
os_atomic_set_bool(&out->active, true);
obs_output_begin_data_capture(out->output, 0);
info("Writing Hybrid MP4 file '%s'...", out->path.array);
return true;
}
static inline bool should_split(struct mp4_output *out, struct encoder_packet *packet)
{
/* split at video frame on primary track */
if (packet->type != OBS_ENCODER_VIDEO || packet->track_idx > 0)
return false;
/* don't split group of pictures */
if (!packet->keyframe)
return false;
if (os_atomic_load_bool(&out->manual_split))
return true;
/* reached maximum file size */
if (out->max_size > 0 && out->cur_size + (int64_t)packet->size >= out->max_size)
return true;
/* reached maximum duration */
if (out->max_time > 0 && packet->dts_usec - out->start_time >= out->max_time)
return true;
return false;
}
static void find_best_filename(struct dstr *path, bool space)
{
int num = 2;
if (!os_file_exists(path->array))
return;
const char *ext = strrchr(path->array, '.');
if (!ext)
return;
size_t extstart = ext - path->array;
struct dstr testpath;
dstr_init_copy_dstr(&testpath, path);
for (;;) {
dstr_resize(&testpath, extstart);
dstr_catf(&testpath, space ? " (%d)" : "_%d", num++);
dstr_cat(&testpath, ext);
if (!os_file_exists(testpath.array)) {
dstr_free(path);
dstr_init_move(path, &testpath);
break;
}
}
}
static void generate_filename(struct mp4_output *out, struct dstr *dst, bool overwrite)
{
obs_data_t *settings = obs_output_get_settings(out->output);
const char *dir = obs_data_get_string(settings, "directory");
const char *fmt = obs_data_get_string(settings, "format");
const char *ext = obs_data_get_string(settings, "extension");
bool space = obs_data_get_bool(settings, "allow_spaces");
char *filename = os_generate_formatted_filename(ext, space, fmt);
dstr_copy(dst, dir);
dstr_replace(dst, "\\", "/");
if (dstr_end(dst) != '/')
dstr_cat_ch(dst, '/');
dstr_cat(dst, filename);
char *slash = strrchr(dst->array, '/');
if (slash) {
*slash = 0;
os_mkdirs(dst->array);
*slash = '/';
}
if (!overwrite)
find_best_filename(dst, space);
bfree(filename);
obs_data_release(settings);
}
static bool change_file(struct mp4_output *out, struct encoder_packet *pkt)
{
uint64_t start_time = os_gettime_ns();
/* finalise file */
for (size_t i = 0; i < out->chapters.num; i++) {
struct chapter *chap = &out->chapters.array[i];
mp4_mux_add_chapter(out->muxer, chap->dts_usec, chap->name);
}
mp4_mux_finalise(out->muxer);
info("Waiting for file writer to finish...");
/* flush/close file and destroy old muxer */
buffered_file_serializer_free(&out->serializer);
mp4_mux_destroy(out->muxer);
for (size_t i = 0; i < out->chapters.num; i++)
bfree(out->chapters.array[i].name);
da_clear(out->chapters);
info("MP4 file split complete. Finalization took %" PRIu64 " ms.", (os_gettime_ns() - start_time) / 1000000);
/* open new file */
generate_filename(out, &out->path, out->allow_overwrite);
info("Changing output file to '%s'", out->path.array);
if (!buffered_file_serializer_init_defaults(&out->serializer, out->path.array)) {
warn("Unable to open MP4 file '%s'", out->path.array);
return false;
}
out->muxer = mp4_mux_create(out->output, &out->serializer, out->flags);
calldata_t cd = {0};
signal_handler_t *sh = obs_output_get_signal_handler(out->output);
calldata_set_string(&cd, "next_file", out->path.array);
signal_handler_signal(sh, "file_changed", &cd);
calldata_free(&cd);
out->cur_size = 0;
out->start_time = pkt->dts_usec;
ts_offset_clear(out);
return true;
}
static void mp4_output_stop(void *data, uint64_t ts)
{
struct mp4_output *out = data;
out->stop_ts = ts / 1000;
os_atomic_set_bool(&out->stopping, true);
}
static void mp4_mux_destroy_task(void *ptr)
{
struct mp4_mux *muxer = ptr;
mp4_mux_destroy(muxer);
}
static void mp4_output_actual_stop(struct mp4_output *out, int code)
{
os_atomic_set_bool(&out->active, false);
uint64_t start_time = os_gettime_ns();
for (size_t i = 0; i < out->chapters.num; i++) {
struct chapter *chap = &out->chapters.array[i];
mp4_mux_add_chapter(out->muxer, chap->dts_usec, chap->name);
}
mp4_mux_finalise(out->muxer);
if (code) {
obs_output_signal_stop(out->output, code);
} else {
obs_output_end_data_capture(out->output);
}
info("Waiting for file writer to finish...");
/* Flush/close output file and destroy muxer */
buffered_file_serializer_free(&out->serializer);
obs_queue_task(OBS_TASK_DESTROY, mp4_mux_destroy_task, out->muxer, false);
out->muxer = NULL;
/* Clear chapter data */
for (size_t i = 0; i < out->chapters.num; i++)
bfree(out->chapters.array[i].name);
da_clear(out->chapters);
info("MP4 file output complete. Finalization took %" PRIu64 " ms.", (os_gettime_ns() - start_time) / 1000000);
}
static void push_back_packet(struct mp4_output *out, struct encoder_packet *packet)
{
struct encoder_packet pkt;
obs_encoder_packet_ref(&pkt, packet);
da_push_back(out->split_buffer, &pkt);
}
static inline bool submit_packet(struct mp4_output *out, struct encoder_packet *pkt)
{
out->total_bytes += pkt->size;
if (!out->split_file_enabled)
return mp4_mux_submit_packet(out->muxer, pkt);
out->cur_size += pkt->size;
/* Apply DTS/PTS offset local packet copy */
struct encoder_packet modified = *pkt;
if (modified.type == OBS_ENCODER_VIDEO) {
modified.dts -= out->video_pts_offsets[modified.track_idx];
modified.pts -= out->video_pts_offsets[modified.track_idx];
} else {
modified.dts -= out->audio_dts_offsets[modified.track_idx];
modified.pts -= out->audio_dts_offsets[modified.track_idx];
}
return mp4_mux_submit_packet(out->muxer, &modified);
}
static void mp4_output_packet(void *data, struct encoder_packet *packet)
{
struct mp4_output *out = data;
pthread_mutex_lock(&out->mutex);
if (!active(out))
goto unlock;
if (!packet) {
mp4_output_actual_stop(out, OBS_OUTPUT_ENCODE_ERROR);
goto unlock;
}
if (stopping(out)) {
if (packet->sys_dts_usec >= (int64_t)out->stop_ts) {
mp4_output_actual_stop(out, 0);
goto unlock;
}
}
if (out->split_file_enabled) {
if (out->split_buffer.num) {
int64_t pts_usec = packet_pts_usec(packet);
struct encoder_packet *first_pkt = out->split_buffer.array;
int64_t first_pts_usec = packet_pts_usec(first_pkt);
if (pts_usec >= first_pts_usec) {
if (packet->type != OBS_ENCODER_AUDIO) {
push_back_packet(out, packet);
goto unlock;
}
if (!change_file(out, first_pkt)) {
mp4_output_actual_stop(out, OBS_OUTPUT_ERROR);
goto unlock;
}
out->split_file_ready = true;
}
} else if (should_split(out, packet)) {
push_back_packet(out, packet);
goto unlock;
}
}
if (out->split_file_ready) {
for (size_t i = 0; i < out->split_buffer.num; i++) {
struct encoder_packet *pkt = &out->split_buffer.array[i];
ts_offset_update(out, pkt);
submit_packet(out, pkt);
obs_encoder_packet_release(pkt);
}
da_free(out->split_buffer);
out->split_file_ready = false;
os_atomic_set_bool(&out->manual_split, false);
}
if (out->split_file_enabled)
ts_offset_update(out, packet);
/* Update PTS for chapter markers */
if (packet->type == OBS_ENCODER_VIDEO && packet->track_idx == 0)
out->last_dts_usec = packet->dts_usec - out->start_time;
submit_packet(out, packet);
if (serializer_get_pos(&out->serializer) == -1)
mp4_output_actual_stop(out, OBS_OUTPUT_ERROR);
unlock:
pthread_mutex_unlock(&out->mutex);
}
static obs_properties_t *mp4_output_properties(void *unused)
{
UNUSED_PARAMETER(unused);
obs_properties_t *props = obs_properties_create();
obs_properties_add_text(props, "path", obs_module_text("MP4Output.FilePath"), OBS_TEXT_DEFAULT);
obs_properties_add_text(props, "muxer_settings", "muxer_settings", OBS_TEXT_DEFAULT);
return props;
}
uint64_t mp4_output_total_bytes(void *data)
{
struct mp4_output *out = data;
return out->total_bytes;
}
struct obs_output_info mp4_output_info = {
.id = "mp4_output",
.flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK_AV | OBS_OUTPUT_CAN_PAUSE,
.encoded_video_codecs = "h264;hevc;av1",
.encoded_audio_codecs = "aac",
.get_name = mp4_output_name,
.create = mp4_output_create,
.destroy = mp4_output_destory,
.start = mp4_output_start,
.stop = mp4_output_stop,
.encoded_packet = mp4_output_packet,
.get_properties = mp4_output_properties,
.get_total_bytes = mp4_output_total_bytes,
};
| 16,187 |
C
|
.c
| 461 | 32.631236 | 111 | 0.697454 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,512 |
rtmp-av1.c
|
obsproject_obs-studio/plugins/obs-outputs/rtmp-av1.c
|
/******************************************************************************
Copyright (C) 2023 by Lain Bailey <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include "rtmp-av1.h"
#include "utils.h"
#include <obs.h>
#include <util/array-serializer.h>
/* Adapted from FFmpeg's libavformat/av1.c for our FLV muxer. */
#define AV1_OBU_SEQUENCE_HEADER 1
#define AV1_OBU_TEMPORAL_DELIMITER 2
#define AV1_OBU_REDUNDANT_FRAME_HEADER 7
#define AV1_OBU_TILE_LIST 8
#define AV1_OBU_PADDING 15
#define AV1_OBU_METADATA 5
#define AV1_OBU_TILE_GROUP 4
#define AV1_OBU_TILE_LIST 8
#define AV1_OBU_FRAME 6
#define AV1_OBU_FRAME_HEADER 3
#define FF_PROFILE_AV1_MAIN 0
#define FF_PROFILE_AV1_HIGH 1
#define FF_PROFILE_AV1_PROFESSIONAL 2
enum frame_type {
AV1_KEY_FRAME,
AV1_INTER_FRAME,
AV1_INTRA_FRAME,
AV1_SWITCH_FRAME,
};
typedef struct AV1SequenceParameters {
uint8_t profile;
uint8_t level;
uint8_t tier;
uint8_t bitdepth;
uint8_t monochrome;
uint8_t chroma_subsampling_x;
uint8_t chroma_subsampling_y;
uint8_t chroma_sample_position;
uint8_t color_description_present_flag;
uint8_t color_primaries;
uint8_t transfer_characteristics;
uint8_t matrix_coefficients;
uint8_t color_range;
} AV1SequenceParameters;
#define MAX_OBU_HEADER_SIZE (2 + 8)
typedef struct Av1GetBitContext {
const uint8_t *buffer, *buffer_end;
int index;
int size_in_bits;
int size_in_bits_plus8;
} Av1GetBitContext;
static inline int init_get_bits_xe(Av1GetBitContext *s, const uint8_t *buffer, int bit_size)
{
int buffer_size;
int ret = 0;
if (bit_size >= INT_MAX - 64 * 8 || bit_size < 0 || !buffer) {
bit_size = 0;
buffer = NULL;
ret = -1;
}
buffer_size = (bit_size + 7) >> 3;
s->buffer = buffer;
s->size_in_bits = bit_size;
s->size_in_bits_plus8 = bit_size + 8;
s->buffer_end = buffer + buffer_size;
s->index = 0;
return ret;
}
static inline int init_get_bits(Av1GetBitContext *s, const uint8_t *buffer, int bit_size)
{
return init_get_bits_xe(s, buffer, bit_size);
}
static inline int init_get_bits8(Av1GetBitContext *s, const uint8_t *buffer, int byte_size)
{
if (byte_size > INT_MAX / 8 || byte_size < 0)
byte_size = -1;
return init_get_bits(s, buffer, byte_size * 8);
}
static inline unsigned int get_bit1(Av1GetBitContext *s)
{
unsigned int index = s->index;
uint8_t result = s->buffer[index >> 3];
result <<= index & 7;
result >>= 8 - 1;
if (s->index < s->size_in_bits_plus8)
index++;
s->index = index;
return result;
}
static inline unsigned int get_bits(Av1GetBitContext *s, unsigned int n)
{
unsigned int out = 0;
for (unsigned int i = 0; i < n; i++)
out = (out << 1) | get_bit1(s);
return out;
}
#define skip_bits get_bits
static inline int get_bits_count(Av1GetBitContext *s)
{
return s->index;
}
static inline int get_bits_left(Av1GetBitContext *gb)
{
return gb->size_in_bits - get_bits_count(gb);
}
#define get_bits_long get_bits
#define skip_bits_long get_bits_long
static inline int64_t leb128(Av1GetBitContext *gb)
{
int64_t ret = 0;
int i;
for (i = 0; i < 8; i++) {
int byte = get_bits(gb, 8);
ret |= (int64_t)(byte & 0x7f) << (i * 7);
if (!(byte & 0x80))
break;
}
return ret;
}
static inline void uvlc(Av1GetBitContext *gb)
{
int leading_zeros = 0;
while (get_bits_left(gb)) {
if (get_bits(gb, 1))
break;
leading_zeros++;
}
if (leading_zeros >= 32)
return;
skip_bits_long(gb, leading_zeros);
}
static inline int parse_obu_header(const uint8_t *buf, int buf_size, int64_t *obu_size, int *start_pos, int *type,
int *temporal_id, int *spatial_id)
{
Av1GetBitContext gb;
int ret, extension_flag, has_size_flag;
size_t size;
ret = init_get_bits8(&gb, buf, min_i32(buf_size, MAX_OBU_HEADER_SIZE));
if (ret < 0)
return ret;
if (get_bits(&gb, 1) != 0) // obu_forbidden_bit
return -1;
*type = get_bits(&gb, 4);
extension_flag = get_bits(&gb, 1);
has_size_flag = get_bits(&gb, 1);
skip_bits(&gb, 1); // obu_reserved_1bit
if (extension_flag) {
*temporal_id = get_bits(&gb, 3);
*spatial_id = get_bits(&gb, 2);
skip_bits(&gb, 3); // extension_header_reserved_3bits
} else {
*temporal_id = *spatial_id = 0;
}
*obu_size = has_size_flag ? leb128(&gb) : buf_size - 1 - extension_flag;
if (get_bits_left(&gb) < 0)
return -1;
*start_pos = get_bits_count(&gb) / 8;
size = (size_t)(*obu_size + *start_pos);
if (size > (size_t)buf_size)
return -1;
assert(size <= INT_MAX);
return (int)size;
}
static inline int get_obu_bit_length(const uint8_t *buf, int size, int type)
{
int v;
/* There are no trailing bits on these */
if (type == AV1_OBU_TILE_GROUP || type == AV1_OBU_TILE_LIST || type == AV1_OBU_FRAME) {
if (size > INT_MAX / 8)
return -1;
else
return size * 8;
}
while (size > 0 && buf[size - 1] == 0)
size--;
if (!size)
return 0;
v = buf[size - 1];
if (size > INT_MAX / 8)
return -1;
size *= 8;
/* Remove the trailing_one_bit and following trailing zeros */
if (v)
size -= ctz32(v) + 1;
return size;
}
static int parse_color_config(AV1SequenceParameters *seq_params, Av1GetBitContext *gb)
{
int twelve_bit = 0;
int high_bitdepth = get_bits(gb, 1);
if (seq_params->profile == FF_PROFILE_AV1_PROFESSIONAL && high_bitdepth)
twelve_bit = get_bits(gb, 1);
seq_params->bitdepth = 8 + (high_bitdepth * 2) + (twelve_bit * 2);
if (seq_params->profile == FF_PROFILE_AV1_HIGH)
seq_params->monochrome = 0;
else
seq_params->monochrome = get_bits(gb, 1);
seq_params->color_description_present_flag = get_bits(gb, 1);
if (seq_params->color_description_present_flag) {
seq_params->color_primaries = get_bits(gb, 8);
seq_params->transfer_characteristics = get_bits(gb, 8);
seq_params->matrix_coefficients = get_bits(gb, 8);
} else {
seq_params->color_primaries = 2;
seq_params->transfer_characteristics = 2;
seq_params->matrix_coefficients = 2;
}
if (seq_params->monochrome) {
seq_params->color_range = get_bits(gb, 1);
seq_params->chroma_subsampling_x = 1;
seq_params->chroma_subsampling_y = 1;
seq_params->chroma_sample_position = 0;
return 0;
} else if (seq_params->color_primaries == 1 && seq_params->transfer_characteristics == 13 &&
seq_params->matrix_coefficients == 0) {
seq_params->chroma_subsampling_x = 0;
seq_params->chroma_subsampling_y = 0;
} else {
seq_params->color_range = get_bits(gb, 1);
if (seq_params->profile == FF_PROFILE_AV1_MAIN) {
seq_params->chroma_subsampling_x = 1;
seq_params->chroma_subsampling_y = 1;
} else if (seq_params->profile == FF_PROFILE_AV1_HIGH) {
seq_params->chroma_subsampling_x = 0;
seq_params->chroma_subsampling_y = 0;
} else {
if (twelve_bit) {
seq_params->chroma_subsampling_x = get_bits(gb, 1);
if (seq_params->chroma_subsampling_x)
seq_params->chroma_subsampling_y = get_bits(gb, 1);
else
seq_params->chroma_subsampling_y = 0;
} else {
seq_params->chroma_subsampling_x = 1;
seq_params->chroma_subsampling_y = 0;
}
}
if (seq_params->chroma_subsampling_x && seq_params->chroma_subsampling_y)
seq_params->chroma_sample_position = get_bits(gb, 2);
}
skip_bits(gb, 1); // separate_uv_delta_q
return 0;
}
static int parse_sequence_header(AV1SequenceParameters *seq_params, const uint8_t *buf, int size)
{
Av1GetBitContext gb;
int reduced_still_picture_header;
int frame_width_bits_minus_1, frame_height_bits_minus_1;
int size_bits, ret;
size_bits = get_obu_bit_length(buf, size, AV1_OBU_SEQUENCE_HEADER);
if (size_bits < 0)
return size_bits;
ret = init_get_bits(&gb, buf, size_bits);
if (ret < 0)
return ret;
memset(seq_params, 0, sizeof(*seq_params));
seq_params->profile = get_bits(&gb, 3);
skip_bits(&gb, 1); // still_picture
reduced_still_picture_header = get_bits(&gb, 1);
if (reduced_still_picture_header) {
seq_params->level = get_bits(&gb, 5);
seq_params->tier = 0;
} else {
int initial_display_delay_present_flag, operating_points_cnt_minus_1;
int decoder_model_info_present_flag, buffer_delay_length_minus_1;
if (get_bits(&gb, 1)) { // timing_info_present_flag
skip_bits_long(&gb, 32); // num_units_in_display_tick
skip_bits_long(&gb, 32); // time_scale
if (get_bits(&gb, 1)) // equal_picture_interval
uvlc(&gb); // num_ticks_per_picture_minus_1
decoder_model_info_present_flag = get_bits(&gb, 1);
if (decoder_model_info_present_flag) {
buffer_delay_length_minus_1 = get_bits(&gb, 5);
skip_bits_long(&gb, 32);
skip_bits(&gb, 10);
}
} else
decoder_model_info_present_flag = 0;
initial_display_delay_present_flag = get_bits(&gb, 1);
operating_points_cnt_minus_1 = get_bits(&gb, 5);
for (int i = 0; i <= operating_points_cnt_minus_1; i++) {
int seq_level_idx, seq_tier;
skip_bits(&gb, 12);
seq_level_idx = get_bits(&gb, 5);
if (seq_level_idx > 7)
seq_tier = get_bits(&gb, 1);
else
seq_tier = 0;
if (decoder_model_info_present_flag) {
if (get_bits(&gb, 1)) {
skip_bits_long(&gb, buffer_delay_length_minus_1 + 1);
skip_bits_long(&gb, buffer_delay_length_minus_1 + 1);
skip_bits(&gb, 1);
}
}
if (initial_display_delay_present_flag) {
if (get_bits(&gb, 1))
skip_bits(&gb, 4);
}
if (i == 0) {
seq_params->level = seq_level_idx;
seq_params->tier = seq_tier;
}
}
}
frame_width_bits_minus_1 = get_bits(&gb, 4);
frame_height_bits_minus_1 = get_bits(&gb, 4);
skip_bits(&gb, frame_width_bits_minus_1 + 1); // max_frame_width_minus_1
skip_bits(&gb,
frame_height_bits_minus_1 + 1); // max_frame_height_minus_1
if (!reduced_still_picture_header) {
if (get_bits(&gb, 1)) // frame_id_numbers_present_flag
skip_bits(&gb, 7);
}
skip_bits(&gb,
3); // use_128x128_superblock (1), enable_filter_intra (1), enable_intra_edge_filter (1)
if (!reduced_still_picture_header) {
int enable_order_hint, seq_force_screen_content_tools;
skip_bits(&gb, 4);
enable_order_hint = get_bits(&gb, 1);
if (enable_order_hint)
skip_bits(&gb, 2);
if (get_bits(&gb, 1)) // seq_choose_screen_content_tools
seq_force_screen_content_tools = 2;
else
seq_force_screen_content_tools = get_bits(&gb, 1);
if (seq_force_screen_content_tools) {
if (!get_bits(&gb, 1)) // seq_choose_integer_mv
skip_bits(&gb, 1); // seq_force_integer_mv
}
if (enable_order_hint)
skip_bits(&gb, 3); // order_hint_bits_minus_1
}
skip_bits(&gb, 3);
parse_color_config(seq_params, &gb);
skip_bits(&gb, 1); // film_grain_params_present
if (get_bits_left(&gb))
return -1;
return 0;
}
size_t obs_parse_av1_header(uint8_t **header, const uint8_t *data, size_t size)
{
if (data[0] & 0x80) {
int config_record_version = data[0] & 0x7f;
if (config_record_version != 1 || size < 4)
return 0;
*header = bmemdup(data, size);
return size;
}
// AV1S init
AV1SequenceParameters seq_params;
int nb_seq = 0, seq_size = 0, meta_size = 0;
const uint8_t *seq = 0, *meta = 0;
uint8_t *buf = (uint8_t *)data;
while (size > 0) {
int64_t obu_size;
int start_pos, type, temporal_id, spatial_id;
assert(size <= INT_MAX);
int len = parse_obu_header(buf, (int)size, &obu_size, &start_pos, &type, &temporal_id, &spatial_id);
if (len < 0)
return 0;
switch (type) {
case AV1_OBU_SEQUENCE_HEADER:
nb_seq++;
if (!obu_size || nb_seq > 1) {
return 0;
}
assert(obu_size <= INT_MAX);
if (parse_sequence_header(&seq_params, buf + start_pos, (int)obu_size) < 0)
return 0;
seq = buf;
seq_size = len;
break;
case AV1_OBU_METADATA:
if (!obu_size)
return 0;
meta = buf;
meta_size = len;
break;
default:
break;
}
size -= len;
buf += len;
}
if (!nb_seq)
return 0;
uint8_t av1header[4];
av1header[0] = (1 << 7) | 1; // marker and version
av1header[1] = (seq_params.profile << 5) | (seq_params.level);
av1header[2] = (seq_params.tier << 7) | (seq_params.bitdepth > 8) << 6 | (seq_params.bitdepth == 12) << 5 |
(seq_params.monochrome) << 4 | (seq_params.chroma_subsampling_x) << 3 |
(seq_params.chroma_subsampling_y) << 2 | (seq_params.chroma_sample_position);
av1header[3] = 0;
struct array_output_data output;
struct serializer s;
array_output_serializer_init(&s, &output);
s_write(&s, av1header, sizeof(av1header));
if (seq_size)
s_write(&s, seq, seq_size);
if (meta_size)
s_write(&s, meta, meta_size);
*header = output.bytes.array;
return output.bytes.num;
}
static void compute_av1_keyframe_priority(const uint8_t *buf, bool *is_keyframe, int *priority)
{
/* Skip if the packet already has a priority, e.g., assigned by the
* encoder implementation (currently QSV/AMF). */
if (*priority)
return;
Av1GetBitContext gb;
init_get_bits8(&gb, buf, 1);
// show_existing_frame
if (get_bit1(&gb))
return;
enum frame_type type = get_bits(&gb, 2);
bool show_frame = get_bit1(&gb);
switch (type) {
case AV1_KEY_FRAME:
*is_keyframe = true;
*priority = 3;
break;
case AV1_INTER_FRAME:
*priority = show_frame ? 1 : 2;
break;
case AV1_INTRA_FRAME:
*priority = 3;
break;
case AV1_SWITCH_FRAME:
*priority = 2;
break;
}
}
static void serialize_av1_data(struct serializer *s, const uint8_t *data, size_t size, bool *is_keyframe, int *priority)
{
uint8_t *buf = (uint8_t *)data;
uint8_t *end = (uint8_t *)data + size;
while (buf < end) {
int64_t obu_size;
int start_pos, type, temporal_id, spatial_id;
assert(end - buf <= INT_MAX);
int len = parse_obu_header(buf, (int)(end - buf), &obu_size, &start_pos, &type, &temporal_id,
&spatial_id);
if (len < 0)
return;
switch (type) {
case AV1_OBU_TEMPORAL_DELIMITER:
case AV1_OBU_REDUNDANT_FRAME_HEADER:
case AV1_OBU_TILE_LIST:
break;
case AV1_OBU_FRAME:
case AV1_OBU_FRAME_HEADER:
compute_av1_keyframe_priority(buf + start_pos, is_keyframe, priority);
/* Falls through. */
default:
s_write(s, buf, len);
size += len;
break;
}
buf += len;
}
}
void obs_parse_av1_packet(struct encoder_packet *av1_packet, const struct encoder_packet *src)
{
struct array_output_data output;
struct serializer s;
long ref = 1;
array_output_serializer_init(&s, &output);
serialize(&s, &ref, sizeof(ref));
*av1_packet = *src;
serialize_av1_data(&s, src->data, src->size, &av1_packet->keyframe, &av1_packet->priority);
av1_packet->data = output.bytes.array + sizeof(ref);
av1_packet->size = output.bytes.num - sizeof(ref);
av1_packet->drop_priority = av1_packet->priority;
}
| 15,154 |
C
|
.c
| 484 | 28.429752 | 120 | 0.671019 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,515 |
rtmp-hevc.c
|
obsproject_obs-studio/plugins/obs-outputs/rtmp-hevc.c
|
/******************************************************************************
Copyright (C) 2023 by Lain Bailey <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include "rtmp-hevc.h"
#include "utils.h"
#include <obs.h>
#include <obs-nal.h>
#include <obs-hevc.h>
#include <util/array-serializer.h>
/* Adapted from FFmpeg's libavformat/hevc.c for our FLV muxer. */
enum { OBS_VPS_INDEX, OBS_SPS_INDEX, OBS_PPS_INDEX, OBS_SEI_PREFIX_INDEX, OBS_SEI_SUFFIX_INDEX, OBS_NB_ARRAYS };
enum {
OBS_HEVC_MAX_VPS_COUNT = 16,
OBS_HEVC_MAX_SPS_COUNT = 16,
OBS_HEVC_MAX_PPS_COUNT = 64,
};
typedef struct HVCCNALUnitArray {
uint8_t array_completeness;
uint8_t NAL_unit_type;
uint16_t numNalus;
struct array_output_data nalUnitData;
struct serializer nalUnit;
} HVCCNALUnitArray;
typedef struct HEVCDecoderConfigurationRecord {
uint8_t general_profile_space;
uint8_t general_tier_flag;
uint8_t general_profile_idc;
uint32_t general_profile_compatibility_flags;
uint64_t general_constraint_indicator_flags;
uint8_t general_level_idc;
uint16_t min_spatial_segmentation_idc;
uint8_t parallelismType;
uint8_t chromaFormat;
uint8_t bitDepthLumaMinus8;
uint8_t bitDepthChromaMinus8;
uint16_t avgFrameRate;
uint8_t constantFrameRate;
uint8_t numTemporalLayers;
uint8_t temporalIdNested;
uint8_t lengthSizeMinusOne;
uint8_t numOfArrays;
HVCCNALUnitArray arrays[OBS_NB_ARRAYS];
} HEVCDecoderConfigurationRecord;
typedef struct HVCCProfileTierLevel {
uint8_t profile_space;
uint8_t tier_flag;
uint8_t profile_idc;
uint32_t profile_compatibility_flags;
uint64_t constraint_indicator_flags;
uint8_t level_idc;
} HVCCProfileTierLevel;
typedef struct HevcGetBitContext {
const uint8_t *buffer, *buffer_end;
uint64_t cache;
unsigned bits_left;
int index;
int size_in_bits;
int size_in_bits_plus8;
} HevcGetBitContext;
static inline uint32_t rb32(const uint8_t *ptr)
{
return (ptr[0] << 24) + (ptr[1] << 16) + (ptr[2] << 8) + ptr[3];
}
static inline void refill_32(HevcGetBitContext *s)
{
s->cache = s->cache | (uint64_t)rb32(s->buffer + (s->index >> 3)) << (32 - s->bits_left);
s->index += 32;
s->bits_left += 32;
}
static inline uint64_t get_val(HevcGetBitContext *s, unsigned n)
{
uint64_t ret;
ret = s->cache >> (64 - n);
s->cache <<= n;
s->bits_left -= n;
return ret;
}
static inline int init_get_bits_xe(HevcGetBitContext *s, const uint8_t *buffer, int bit_size)
{
int buffer_size;
int ret = 0;
if (bit_size >= INT_MAX - 64 * 8 || bit_size < 0 || !buffer) {
bit_size = 0;
buffer = NULL;
ret = -1;
}
buffer_size = (bit_size + 7) >> 3;
s->buffer = buffer;
s->size_in_bits = bit_size;
s->size_in_bits_plus8 = bit_size + 8;
s->buffer_end = buffer + buffer_size;
s->index = 0;
s->cache = 0;
s->bits_left = 0;
refill_32(s);
return ret;
}
static inline int init_get_bits(HevcGetBitContext *s, const uint8_t *buffer, int bit_size)
{
return init_get_bits_xe(s, buffer, bit_size);
}
static inline int init_get_bits8(HevcGetBitContext *s, const uint8_t *buffer, int byte_size)
{
if (byte_size > INT_MAX / 8 || byte_size < 0)
byte_size = -1;
return init_get_bits(s, buffer, byte_size * 8);
}
static inline unsigned int get_bits(HevcGetBitContext *s, unsigned int n)
{
register unsigned int tmp;
if (n > s->bits_left) {
refill_32(s);
}
tmp = (unsigned int)get_val(s, n);
return tmp;
}
#define skip_bits get_bits
static inline int get_bits_count(HevcGetBitContext *s)
{
return s->index - s->bits_left;
}
static inline int get_bits_left(HevcGetBitContext *gb)
{
return gb->size_in_bits - get_bits_count(gb);
}
static inline unsigned int get_bits_long(HevcGetBitContext *s, int n)
{
if (!n)
return 0;
return get_bits(s, n);
}
#define skip_bits_long get_bits_long
static inline uint64_t get_bits64(HevcGetBitContext *s, int n)
{
if (n <= 32) {
return get_bits_long(s, n);
} else {
uint64_t ret = (uint64_t)get_bits_long(s, n - 32) << 32;
return ret | get_bits_long(s, 32);
}
}
static inline int ilog2(unsigned x)
{
return (31 - clz32(x | 1));
}
static inline unsigned show_val(const HevcGetBitContext *s, unsigned n)
{
return s->cache & ((UINT64_C(1) << n) - 1);
}
static inline unsigned int show_bits(HevcGetBitContext *s, unsigned int n)
{
register unsigned int tmp;
if (n > s->bits_left)
refill_32(s);
tmp = show_val(s, n);
return tmp;
}
static inline unsigned int show_bits_long(HevcGetBitContext *s, int n)
{
if (n <= 25) {
return show_bits(s, n);
} else {
HevcGetBitContext gb = *s;
return get_bits_long(&gb, n);
}
}
static inline unsigned get_ue_golomb_long(HevcGetBitContext *gb)
{
unsigned buf, log;
buf = show_bits_long(gb, 32);
log = 31 - ilog2(buf);
skip_bits_long(gb, log);
return get_bits_long(gb, log + 1) - 1;
}
static inline int get_se_golomb_long(HevcGetBitContext *gb)
{
unsigned int buf = get_ue_golomb_long(gb);
int sign = (buf & 1) - 1;
return ((buf >> 1) ^ sign) + 1;
}
static inline bool has_start_code(const uint8_t *data, size_t size)
{
if (size > 3 && data[0] == 0 && data[1] == 0 && data[2] == 1)
return true;
if (size > 4 && data[0] == 0 && data[1] == 0 && data[2] == 0 && data[3] == 1)
return true;
return false;
}
uint8_t *ff_nal_unit_extract_rbsp(uint8_t *dst, const uint8_t *src, int src_len, uint32_t *dst_len, int header_len)
{
int i, len;
/* NAL unit header */
i = len = 0;
while (i < header_len && i < src_len)
dst[len++] = src[i++];
while (i + 2 < src_len)
if (!src[i] && !src[i + 1] && src[i + 2] == 3) {
dst[len++] = src[i++];
dst[len++] = src[i++];
i++; // remove emulation_prevention_three_byte
} else
dst[len++] = src[i++];
while (i < src_len)
dst[len++] = src[i++];
memset(dst + len, 0, 64);
*dst_len = (uint32_t)len;
return dst;
}
static int hvcc_array_add_nal_unit(uint8_t *nal_buf, uint32_t nal_size, uint8_t nal_type, int ps_array_completeness,
HVCCNALUnitArray *array)
{
s_wb16(&array->nalUnit, nal_size);
s_write(&array->nalUnit, nal_buf, nal_size);
array->NAL_unit_type = nal_type;
array->numNalus++;
if (nal_type == OBS_HEVC_NAL_VPS || nal_type == OBS_HEVC_NAL_SPS || nal_type == OBS_HEVC_NAL_PPS)
array->array_completeness = ps_array_completeness;
return 0;
}
static void nal_unit_parse_header(HevcGetBitContext *gb, uint8_t *nal_type)
{
skip_bits(gb, 1); // forbidden_zero_bit
*nal_type = get_bits(gb, 6);
get_bits(gb, 9);
}
static void hvcc_update_ptl(HEVCDecoderConfigurationRecord *hvcc, HVCCProfileTierLevel *ptl)
{
hvcc->general_profile_space = ptl->profile_space;
if (hvcc->general_tier_flag < ptl->tier_flag)
hvcc->general_level_idc = ptl->level_idc;
else
hvcc->general_level_idc = max_u8(hvcc->general_level_idc, ptl->level_idc);
hvcc->general_tier_flag = max_u8(hvcc->general_tier_flag, ptl->tier_flag);
hvcc->general_profile_idc = max_u8(hvcc->general_profile_idc, ptl->profile_idc);
hvcc->general_profile_compatibility_flags &= ptl->profile_compatibility_flags;
hvcc->general_constraint_indicator_flags &= ptl->constraint_indicator_flags;
}
static void hvcc_parse_ptl(HevcGetBitContext *gb, HEVCDecoderConfigurationRecord *hvcc,
unsigned int max_sub_layers_minus1)
{
unsigned int i;
HVCCProfileTierLevel general_ptl;
uint8_t sub_layer_profile_present_flag[7]; // max sublayers
uint8_t sub_layer_level_present_flag[7]; // max sublayers
general_ptl.profile_space = get_bits(gb, 2);
general_ptl.tier_flag = get_bits(gb, 1);
general_ptl.profile_idc = get_bits(gb, 5);
general_ptl.profile_compatibility_flags = get_bits_long(gb, 32);
general_ptl.constraint_indicator_flags = get_bits64(gb, 48);
general_ptl.level_idc = get_bits(gb, 8);
hvcc_update_ptl(hvcc, &general_ptl);
for (i = 0; i < max_sub_layers_minus1; i++) {
sub_layer_profile_present_flag[i] = get_bits(gb, 1);
sub_layer_level_present_flag[i] = get_bits(gb, 1);
}
// skip the rest
if (max_sub_layers_minus1 > 0)
for (i = max_sub_layers_minus1; i < 8; i++)
skip_bits(gb, 2);
for (i = 0; i < max_sub_layers_minus1; i++) {
if (sub_layer_profile_present_flag[i]) {
skip_bits_long(gb, 32);
skip_bits_long(gb, 32);
skip_bits(gb, 24);
}
if (sub_layer_level_present_flag[i])
skip_bits(gb, 8);
}
}
static int hvcc_parse_vps(HevcGetBitContext *gb, HEVCDecoderConfigurationRecord *hvcc)
{
unsigned int vps_max_sub_layers_minus1;
skip_bits(gb, 12);
vps_max_sub_layers_minus1 = get_bits(gb, 3);
hvcc->numTemporalLayers = max_u8(hvcc->numTemporalLayers, vps_max_sub_layers_minus1 + 1);
skip_bits(gb, 17);
hvcc_parse_ptl(gb, hvcc, vps_max_sub_layers_minus1);
return 0;
}
#define HEVC_MAX_SHORT_TERM_REF_PIC_SETS 64
static void skip_scaling_list_data(HevcGetBitContext *gb)
{
int i, j, k, num_coeffs;
for (i = 0; i < 4; i++) {
for (j = 0; j < (i == 3 ? 2 : 6); j++) {
if (!get_bits(gb, 1))
get_ue_golomb_long(gb);
else {
num_coeffs = min_i32(64, 1 << (4 + (i << 1)));
if (i > 1)
get_se_golomb_long(gb);
for (k = 0; k < num_coeffs; k++)
get_se_golomb_long(gb);
}
}
}
}
static int parse_rps(HevcGetBitContext *gb, unsigned int rps_idx, unsigned int num_rps,
unsigned int num_delta_pocs[HEVC_MAX_SHORT_TERM_REF_PIC_SETS])
{
unsigned int i;
if (rps_idx && get_bits(gb, 1)) { // inter_ref_pic_set_prediction_flag
/* this should only happen for slice headers, and this isn't one */
if (rps_idx >= num_rps)
return -1;
get_bits(gb, 1); // delta_rps_sign
get_ue_golomb_long(gb); // abs_delta_rps_minus1
num_delta_pocs[rps_idx] = 0;
for (i = 0; i <= num_delta_pocs[rps_idx - 1]; i++) {
uint8_t use_delta_flag = 0;
uint8_t used_by_curr_pic_flag = get_bits(gb, 1);
if (!used_by_curr_pic_flag)
use_delta_flag = get_bits(gb, 1);
if (used_by_curr_pic_flag || use_delta_flag)
num_delta_pocs[rps_idx]++;
}
} else {
unsigned int num_negative_pics = get_ue_golomb_long(gb);
unsigned int num_positive_pics = get_ue_golomb_long(gb);
if ((num_positive_pics + (uint64_t)num_negative_pics) * 2 > (uint64_t)get_bits_left(gb))
return -1;
num_delta_pocs[rps_idx] = num_negative_pics + num_positive_pics;
for (i = 0; i < num_negative_pics; i++) {
get_ue_golomb_long(gb); // delta_poc_s0_minus1[rps_idx]
get_bits(gb, 1); // used_by_curr_pic_s0_flag[rps_idx]
}
for (i = 0; i < num_positive_pics; i++) {
get_ue_golomb_long(gb); // delta_poc_s1_minus1[rps_idx]
get_bits(gb, 1); // used_by_curr_pic_s1_flag[rps_idx]
}
}
return 0;
}
static void skip_sub_layer_hrd_parameters(HevcGetBitContext *gb, unsigned int cpb_cnt_minus1,
uint8_t sub_pic_hrd_params_present_flag)
{
unsigned int i;
for (i = 0; i <= cpb_cnt_minus1; i++) {
get_ue_golomb_long(gb); // bit_rate_value_minus1
get_ue_golomb_long(gb); // cpb_size_value_minus1
if (sub_pic_hrd_params_present_flag) {
get_ue_golomb_long(gb); // cpb_size_du_value_minus1
get_ue_golomb_long(gb); // bit_rate_du_value_minus1
}
get_bits(gb, 1); // cbr_flag
}
}
static int skip_hrd_parameters(HevcGetBitContext *gb, uint8_t cprms_present_flag, unsigned int max_sub_layers_minus1)
{
unsigned int i;
uint8_t sub_pic_hrd_params_present_flag = 0;
uint8_t nal_hrd_parameters_present_flag = 0;
uint8_t vcl_hrd_parameters_present_flag = 0;
if (cprms_present_flag) {
nal_hrd_parameters_present_flag = get_bits(gb, 1);
vcl_hrd_parameters_present_flag = get_bits(gb, 1);
if (nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag) {
sub_pic_hrd_params_present_flag = get_bits(gb, 1);
if (sub_pic_hrd_params_present_flag)
get_bits(gb, 19);
get_bits(gb, 8);
if (sub_pic_hrd_params_present_flag)
get_bits(gb, 4);
get_bits(gb, 15);
}
}
for (i = 0; i <= max_sub_layers_minus1; i++) {
unsigned int cpb_cnt_minus1 = 0;
uint8_t low_delay_hrd_flag = 0;
uint8_t fixed_pic_rate_within_cvs_flag = 0;
uint8_t fixed_pic_rate_general_flag = get_bits(gb, 1);
if (!fixed_pic_rate_general_flag)
fixed_pic_rate_within_cvs_flag = get_bits(gb, 1);
if (fixed_pic_rate_within_cvs_flag)
get_ue_golomb_long(gb);
else
low_delay_hrd_flag = get_bits(gb, 1);
if (!low_delay_hrd_flag) {
cpb_cnt_minus1 = get_ue_golomb_long(gb);
if (cpb_cnt_minus1 > 31)
return -1;
}
if (nal_hrd_parameters_present_flag)
skip_sub_layer_hrd_parameters(gb, cpb_cnt_minus1, sub_pic_hrd_params_present_flag);
if (vcl_hrd_parameters_present_flag)
skip_sub_layer_hrd_parameters(gb, cpb_cnt_minus1, sub_pic_hrd_params_present_flag);
}
return 0;
}
static void hvcc_parse_vui(HevcGetBitContext *gb, HEVCDecoderConfigurationRecord *hvcc,
unsigned int max_sub_layers_minus1)
{
unsigned int min_spatial_segmentation_idc;
if (get_bits(gb, 1)) // aspect_ratio_info_present_flag
if (get_bits(gb, 8) == 255) // aspect_ratio_idc
get_bits_long(gb,
32); // sar_width u(16), sar_height u(16)
if (get_bits(gb, 1)) // overscan_info_present_flag
get_bits(gb, 1); // overscan_appropriate_flag
if (get_bits(gb, 1)) { // video_signal_type_present_flag
get_bits(gb,
4); // video_format u(3), video_full_range_flag u(1)
if (get_bits(gb, 1)) // colour_description_present_flag
get_bits(gb, 24);
}
if (get_bits(gb, 1)) {
get_ue_golomb_long(gb);
get_ue_golomb_long(gb);
}
get_bits(gb, 3);
if (get_bits(gb, 1)) { // default_display_window_flag
get_ue_golomb_long(gb); // def_disp_win_left_offset
get_ue_golomb_long(gb); // def_disp_win_right_offset
get_ue_golomb_long(gb); // def_disp_win_top_offset
get_ue_golomb_long(gb); // def_disp_win_bottom_offset
}
if (get_bits(gb, 1)) { // vui_timing_info_present_flag
// skip timing info
get_bits_long(gb, 32); // num_units_in_tick
get_bits_long(gb, 32); // time_scale
if (get_bits(gb, 1)) // poc_proportional_to_timing_flag
get_ue_golomb_long(gb); // num_ticks_poc_diff_one_minus1
if (get_bits(gb, 1)) // vui_hrd_parameters_present_flag
skip_hrd_parameters(gb, 1, max_sub_layers_minus1);
}
if (get_bits(gb, 1)) { // bitstream_restriction_flag
get_bits(gb, 3);
min_spatial_segmentation_idc = get_ue_golomb_long(gb);
hvcc->min_spatial_segmentation_idc =
min_u16(hvcc->min_spatial_segmentation_idc, min_spatial_segmentation_idc);
get_ue_golomb_long(gb); // max_bytes_per_pic_denom
get_ue_golomb_long(gb); // max_bits_per_min_cu_denom
get_ue_golomb_long(gb); // log2_max_mv_length_horizontal
get_ue_golomb_long(gb); // log2_max_mv_length_vertical
}
}
static int hvcc_parse_sps(HevcGetBitContext *gb, HEVCDecoderConfigurationRecord *hvcc)
{
unsigned int i, sps_max_sub_layers_minus1, log2_max_pic_order_cnt_lsb_minus4;
unsigned int num_short_term_ref_pic_sets, num_delta_pocs[HEVC_MAX_SHORT_TERM_REF_PIC_SETS];
get_bits(gb, 4); // sps_video_parameter_set_id
sps_max_sub_layers_minus1 = get_bits(gb, 3);
hvcc->numTemporalLayers = max_u8(hvcc->numTemporalLayers, sps_max_sub_layers_minus1 + 1);
hvcc->temporalIdNested = get_bits(gb, 1);
hvcc_parse_ptl(gb, hvcc, sps_max_sub_layers_minus1);
get_ue_golomb_long(gb); // sps_seq_parameter_set_id
hvcc->chromaFormat = get_ue_golomb_long(gb);
if (hvcc->chromaFormat == 3)
get_bits(gb, 1); // separate_colour_plane_flag
get_ue_golomb_long(gb); // pic_width_in_luma_samples
get_ue_golomb_long(gb); // pic_height_in_luma_samples
if (get_bits(gb, 1)) { // conformance_window_flag
get_ue_golomb_long(gb); // conf_win_left_offset
get_ue_golomb_long(gb); // conf_win_right_offset
get_ue_golomb_long(gb); // conf_win_top_offset
get_ue_golomb_long(gb); // conf_win_bottom_offset
}
hvcc->bitDepthLumaMinus8 = get_ue_golomb_long(gb);
hvcc->bitDepthChromaMinus8 = get_ue_golomb_long(gb);
log2_max_pic_order_cnt_lsb_minus4 = get_ue_golomb_long(gb);
/* sps_sub_layer_ordering_info_present_flag */
i = get_bits(gb, 1) ? 0 : sps_max_sub_layers_minus1;
for (; i <= sps_max_sub_layers_minus1; i++) {
get_ue_golomb_long(gb); // max_dec_pic_buffering_minus1
get_ue_golomb_long(gb); // max_num_reorder_pics
get_ue_golomb_long(gb); // max_latency_increase_plus1
}
get_ue_golomb_long(gb); // log2_min_luma_coding_block_size_minus3
get_ue_golomb_long(gb); // log2_diff_max_min_luma_coding_block_size
get_ue_golomb_long(gb); // log2_min_transform_block_size_minus2
get_ue_golomb_long(gb); // log2_diff_max_min_transform_block_size
get_ue_golomb_long(gb); // max_transform_hierarchy_depth_inter
get_ue_golomb_long(gb); // max_transform_hierarchy_depth_intra
if (get_bits(gb, 1) && // scaling_list_enabled_flag
get_bits(gb, 1)) // sps_scaling_list_data_present_flag
skip_scaling_list_data(gb);
get_bits(gb, 1); // amp_enabled_flag
get_bits(gb, 1); // sample_adaptive_offset_enabled_flag
if (get_bits(gb, 1)) { // pcm_enabled_flag
get_bits(gb, 4); // pcm_sample_bit_depth_luma_minus1
get_bits(gb, 4); // pcm_sample_bit_depth_chroma_minus1
get_ue_golomb_long(gb); // log2_min_pcm_luma_coding_block_size_minus3
get_ue_golomb_long(gb); // log2_diff_max_min_pcm_luma_coding_block_size
get_bits(gb, 1); // pcm_loop_filter_disabled_flag
}
num_short_term_ref_pic_sets = get_ue_golomb_long(gb);
if (num_short_term_ref_pic_sets > HEVC_MAX_SHORT_TERM_REF_PIC_SETS)
return -1;
for (i = 0; i < num_short_term_ref_pic_sets; i++) {
int ret = parse_rps(gb, i, num_short_term_ref_pic_sets, num_delta_pocs);
if (ret < 0)
return ret;
}
if (get_bits(gb, 1)) { // long_term_ref_pics_present_flag
unsigned num_long_term_ref_pics_sps = get_ue_golomb_long(gb);
if (num_long_term_ref_pics_sps > 31U)
return -1;
for (i = 0; i < num_long_term_ref_pics_sps; i++) { // num_long_term_ref_pics_sps
int len = min_i32(log2_max_pic_order_cnt_lsb_minus4 + 4, 16);
get_bits(gb, len); // lt_ref_pic_poc_lsb_sps[i]
get_bits(gb, 1); // used_by_curr_pic_lt_sps_flag[i]
}
}
get_bits(gb, 1); // sps_temporal_mvp_enabled_flag
get_bits(gb, 1); // strong_intra_smoothing_enabled_flag
if (get_bits(gb, 1)) // vui_parameters_present_flag
hvcc_parse_vui(gb, hvcc, sps_max_sub_layers_minus1);
/* nothing useful for hvcC past this point */
return 0;
}
static int hvcc_parse_pps(HevcGetBitContext *gb, HEVCDecoderConfigurationRecord *hvcc)
{
uint8_t tiles_enabled_flag, entropy_coding_sync_enabled_flag;
get_ue_golomb_long(gb); // pps_pic_parameter_set_id
get_ue_golomb_long(gb); // pps_seq_parameter_set_id
get_bits(gb, 7);
get_ue_golomb_long(gb); // num_ref_idx_l0_default_active_minus1
get_ue_golomb_long(gb); // num_ref_idx_l1_default_active_minus1
get_se_golomb_long(gb); // init_qp_minus26
get_bits(gb, 2);
if (get_bits(gb, 1)) // cu_qp_delta_enabled_flag
get_ue_golomb_long(gb); // diff_cu_qp_delta_depth
get_se_golomb_long(gb); // pps_cb_qp_offset
get_se_golomb_long(gb); // pps_cr_qp_offset
get_bits(gb, 4);
tiles_enabled_flag = get_bits(gb, 1);
entropy_coding_sync_enabled_flag = get_bits(gb, 1);
if (entropy_coding_sync_enabled_flag && tiles_enabled_flag)
hvcc->parallelismType = 0; // mixed-type parallel decoding
else if (entropy_coding_sync_enabled_flag)
hvcc->parallelismType = 3; // wavefront-based parallel decoding
else if (tiles_enabled_flag)
hvcc->parallelismType = 2; // tile-based parallel decoding
else
hvcc->parallelismType = 1; // slice-based parallel decoding
/* nothing useful for hvcC past this point */
return 0;
}
static int hvcc_add_nal_unit(uint8_t *nal_buf, uint32_t nal_size, int ps_array_completeness,
HEVCDecoderConfigurationRecord *hvcc, unsigned array_idx)
{
int ret = 0;
HevcGetBitContext gbc;
uint8_t nal_type;
uint8_t *rbsp_buf;
uint32_t rbsp_size;
uint8_t *dst;
dst = bmalloc(nal_size + 64);
rbsp_buf = ff_nal_unit_extract_rbsp(dst, nal_buf, nal_size, &rbsp_size, 2);
if (!rbsp_buf) {
ret = -1;
goto end;
}
ret = init_get_bits8(&gbc, rbsp_buf, rbsp_size);
if (ret < 0)
goto end;
nal_unit_parse_header(&gbc, &nal_type);
ret = hvcc_array_add_nal_unit(nal_buf, nal_size, nal_type, ps_array_completeness, &hvcc->arrays[array_idx]);
if (ret < 0)
goto end;
if (hvcc->arrays[array_idx].numNalus == 1)
hvcc->numOfArrays++;
if (nal_type == OBS_HEVC_NAL_VPS)
ret = hvcc_parse_vps(&gbc, hvcc);
else if (nal_type == OBS_HEVC_NAL_SPS)
ret = hvcc_parse_sps(&gbc, hvcc);
else if (nal_type == OBS_HEVC_NAL_PPS)
ret = hvcc_parse_pps(&gbc, hvcc);
if (ret < 0)
goto end;
end:
bfree(dst);
return ret;
}
size_t obs_parse_hevc_header(uint8_t **header, const uint8_t *data, size_t size)
{
const uint8_t *start;
const uint8_t *end;
if (!has_start_code(data, size)) {
*header = bmemdup(data, size);
return size;
}
if (size < 6)
return 0; // invalid
if (*data == 1) { // already hvcC-formatted
*header = bmemdup(data, size);
return size;
}
struct array_output_data nals;
struct serializer sn;
array_output_serializer_init(&sn, &nals);
const uint8_t *nal_start, *nal_end;
start = data;
end = data + size;
size = 0; // reset size
nal_start = obs_nal_find_startcode(start, end);
for (;;) {
while (nal_start < end && !*(nal_start++))
;
if (nal_start == end)
break;
nal_end = obs_nal_find_startcode(nal_start, end);
assert(nal_end - nal_start <= INT_MAX);
s_wb32(&sn, (uint32_t)(nal_end - nal_start));
s_write(&sn, nal_start, nal_end - nal_start);
size += 4 + nal_end - nal_start;
nal_start = nal_end;
}
if (size == 0)
goto done;
start = nals.bytes.array;
end = nals.bytes.array + nals.bytes.num;
// HVCC init
HEVCDecoderConfigurationRecord hvcc;
memset(&hvcc, 0, sizeof(HEVCDecoderConfigurationRecord));
hvcc.lengthSizeMinusOne = 3; // 4 bytes
hvcc.general_profile_compatibility_flags = 0xffffffff; // all bits set
hvcc.general_constraint_indicator_flags = 0xffffffffffff; // all bits set
hvcc.min_spatial_segmentation_idc = 4096 + 1; // assume invalid value
for (unsigned i = 0; i < OBS_NB_ARRAYS; i++) {
HVCCNALUnitArray *const array = &hvcc.arrays[i];
array_output_serializer_init(&array->nalUnit, &array->nalUnitData);
}
uint8_t *buf = (uint8_t *)start;
while (end - buf > 4) {
uint32_t len = rb32(buf);
assert((end - buf - 4) <= INT_MAX);
len = min_u32(len, (uint32_t)(end - buf - 4));
uint8_t type = (buf[4] >> 1) & 0x3f;
buf += 4;
for (unsigned i = 0; i < OBS_NB_ARRAYS; i++) {
static const uint8_t array_idx_to_type[] = {OBS_HEVC_NAL_VPS, OBS_HEVC_NAL_SPS,
OBS_HEVC_NAL_PPS, OBS_HEVC_NAL_SEI_PREFIX,
OBS_HEVC_NAL_SEI_SUFFIX};
if (type == array_idx_to_type[i]) {
int ps_array_completeness = 1;
int ret = hvcc_add_nal_unit(buf, len, ps_array_completeness, &hvcc, i);
if (ret < 0)
goto free;
break;
}
}
buf += len;
}
// write hvcc data
uint16_t vps_count, sps_count, pps_count;
if (hvcc.min_spatial_segmentation_idc > 4096) // invalid?
hvcc.min_spatial_segmentation_idc = 0;
if (!hvcc.min_spatial_segmentation_idc)
hvcc.parallelismType = 0;
hvcc.avgFrameRate = 0;
hvcc.constantFrameRate = 0;
vps_count = hvcc.arrays[OBS_VPS_INDEX].numNalus;
sps_count = hvcc.arrays[OBS_SPS_INDEX].numNalus;
pps_count = hvcc.arrays[OBS_PPS_INDEX].numNalus;
if (!vps_count || vps_count > OBS_HEVC_MAX_VPS_COUNT || !sps_count || sps_count > OBS_HEVC_MAX_SPS_COUNT ||
!pps_count || pps_count > OBS_HEVC_MAX_PPS_COUNT)
goto free;
struct array_output_data output;
struct serializer s;
array_output_serializer_init(&s, &output);
s_w8(&s, 1); // configurationVersion, always 1
s_w8(&s, hvcc.general_profile_space << 6 | hvcc.general_tier_flag << 5 | hvcc.general_profile_idc);
s_wb32(&s, hvcc.general_profile_compatibility_flags);
s_wb32(&s, (uint32_t)(hvcc.general_constraint_indicator_flags >> 16));
s_wb16(&s, (uint16_t)(hvcc.general_constraint_indicator_flags));
s_w8(&s, hvcc.general_level_idc);
s_wb16(&s, hvcc.min_spatial_segmentation_idc | 0xf000);
s_w8(&s, hvcc.parallelismType | 0xfc);
s_w8(&s, hvcc.chromaFormat | 0xfc);
s_w8(&s, hvcc.bitDepthLumaMinus8 | 0xf8);
s_w8(&s, hvcc.bitDepthChromaMinus8 | 0xf8);
s_wb16(&s, hvcc.avgFrameRate);
s_w8(&s, hvcc.constantFrameRate << 6 | hvcc.numTemporalLayers << 3 | hvcc.temporalIdNested << 2 |
hvcc.lengthSizeMinusOne);
s_w8(&s, hvcc.numOfArrays);
for (unsigned i = 0; i < OBS_NB_ARRAYS; i++) {
const HVCCNALUnitArray *const array = &hvcc.arrays[i];
if (!array->numNalus)
continue;
s_w8(&s, (array->array_completeness << 7) | (array->NAL_unit_type & 0x3f));
s_wb16(&s, array->numNalus);
s_write(&s, array->nalUnitData.bytes.array, array->nalUnitData.bytes.num);
}
*header = output.bytes.array;
size = output.bytes.num;
free:
for (unsigned i = 0; i < OBS_NB_ARRAYS; i++) {
HVCCNALUnitArray *const array = &hvcc.arrays[i];
array->numNalus = 0;
array_output_serializer_free(&array->nalUnitData);
}
done:
array_output_serializer_free(&nals);
return size;
}
| 25,493 |
C
|
.c
| 706 | 33.44051 | 117 | 0.683783 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,519 |
rtmp-hevc.h
|
obsproject_obs-studio/plugins/obs-outputs/rtmp-hevc.h
|
/******************************************************************************
Copyright (C) 2023 by Lain Bailey <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#pragma once
#include <stdint.h>
#include <stddef.h>
extern size_t obs_parse_hevc_header(uint8_t **header, const uint8_t *data, size_t size);
| 1,018 |
C
|
.c
| 17 | 55.941176 | 88 | 0.635176 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,531 |
screencast-portal.c
|
obsproject_obs-studio/plugins/linux-pipewire/screencast-portal.c
|
/* screencast-portal.c
*
* Copyright 2022 Georges Basile Stavracas Neto <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "pipewire.h"
#include "portal.h"
#include <gio/gunixfdlist.h>
enum portal_capture_type {
PORTAL_CAPTURE_TYPE_MONITOR = 1 << 0,
PORTAL_CAPTURE_TYPE_WINDOW = 1 << 1,
PORTAL_CAPTURE_TYPE_VIRTUAL = 1 << 2,
};
enum portal_cursor_mode {
PORTAL_CURSOR_MODE_HIDDEN = 1 << 0,
PORTAL_CURSOR_MODE_EMBEDDED = 1 << 1,
PORTAL_CURSOR_MODE_METADATA = 1 << 2,
};
enum obs_portal_capture_type {
OBS_PORTAL_CAPTURE_TYPE_MONITOR = PORTAL_CAPTURE_TYPE_MONITOR,
OBS_PORTAL_CAPTURE_TYPE_WINDOW = PORTAL_CAPTURE_TYPE_WINDOW,
OBS_PORTAL_CAPTURE_TYPE_UNIFIED = PORTAL_CAPTURE_TYPE_MONITOR | PORTAL_CAPTURE_TYPE_WINDOW,
};
struct screencast_portal_capture {
enum obs_portal_capture_type capture_type;
GCancellable *cancellable;
char *session_handle;
char *restore_token;
obs_source_t *source;
obs_data_t *settings;
uint32_t pipewire_node;
bool cursor_visible;
obs_pipewire *obs_pw;
obs_pipewire_stream *obs_pw_stream;
};
/* ------------------------------------------------- */
static GDBusProxy *screencast_proxy = NULL;
static void ensure_screencast_portal_proxy(void)
{
g_autoptr(GError) error = NULL;
if (!screencast_proxy) {
screencast_proxy = g_dbus_proxy_new_sync(portal_get_dbus_connection(), G_DBUS_PROXY_FLAGS_NONE, NULL,
"org.freedesktop.portal.Desktop",
"/org/freedesktop/portal/desktop",
"org.freedesktop.portal.ScreenCast", NULL, &error);
if (error) {
blog(LOG_WARNING, "[portals] Error retrieving D-Bus proxy: %s", error->message);
return;
}
}
}
static GDBusProxy *get_screencast_portal_proxy(void)
{
ensure_screencast_portal_proxy();
return screencast_proxy;
}
static uint32_t get_available_capture_types(void)
{
g_autoptr(GVariant) cached_source_types = NULL;
uint32_t available_source_types;
ensure_screencast_portal_proxy();
if (!screencast_proxy)
return 0;
cached_source_types = g_dbus_proxy_get_cached_property(screencast_proxy, "AvailableSourceTypes");
available_source_types = cached_source_types ? g_variant_get_uint32(cached_source_types) : 0;
return available_source_types;
}
static uint32_t get_available_cursor_modes(void)
{
g_autoptr(GVariant) cached_cursor_modes = NULL;
uint32_t available_cursor_modes;
ensure_screencast_portal_proxy();
if (!screencast_proxy)
return 0;
cached_cursor_modes = g_dbus_proxy_get_cached_property(screencast_proxy, "AvailableCursorModes");
available_cursor_modes = cached_cursor_modes ? g_variant_get_uint32(cached_cursor_modes) : 0;
return available_cursor_modes;
}
static uint32_t get_screencast_version(void)
{
g_autoptr(GVariant) cached_version = NULL;
uint32_t version;
ensure_screencast_portal_proxy();
if (!screencast_proxy)
return 0;
cached_version = g_dbus_proxy_get_cached_property(screencast_proxy, "version");
version = cached_version ? g_variant_get_uint32(cached_version) : 0;
return version;
}
/* ------------------------------------------------- */
static const char *capture_type_to_string(enum obs_portal_capture_type capture_type)
{
switch (capture_type) {
case OBS_PORTAL_CAPTURE_TYPE_MONITOR:
return "monitor";
case OBS_PORTAL_CAPTURE_TYPE_WINDOW:
return "window";
case OBS_PORTAL_CAPTURE_TYPE_UNIFIED:
return "monitor and window";
default:
return "unknown";
}
}
/* ------------------------------------------------- */
static void on_pipewire_remote_opened_cb(GObject *source, GAsyncResult *res, void *user_data)
{
struct obs_pipwire_connect_stream_info connect_info;
struct screencast_portal_capture *capture;
g_autoptr(GUnixFDList) fd_list = NULL;
g_autoptr(GVariant) result = NULL;
g_autoptr(GError) error = NULL;
int pipewire_fd;
int fd_index;
capture = user_data;
result = g_dbus_proxy_call_with_unix_fd_list_finish(G_DBUS_PROXY(source), &fd_list, res, &error);
if (error) {
if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
blog(LOG_ERROR, "[pipewire] Error retrieving pipewire fd: %s", error->message);
return;
}
g_variant_get(result, "(h)", &fd_index, &error);
pipewire_fd = g_unix_fd_list_get(fd_list, fd_index, &error);
if (error) {
if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
blog(LOG_ERROR, "[pipewire] Error retrieving pipewire fd: %s", error->message);
return;
}
capture->obs_pw = obs_pipewire_connect_fd(pipewire_fd, NULL, NULL);
if (!capture->obs_pw)
return;
connect_info = (struct obs_pipwire_connect_stream_info){
.stream_name = "OBS Studio",
.stream_properties = pw_properties_new(PW_KEY_MEDIA_TYPE, "Video", PW_KEY_MEDIA_CATEGORY, "Capture",
PW_KEY_MEDIA_ROLE, "Screen", NULL),
.screencast =
{
.cursor_visible = capture->cursor_visible,
},
};
capture->obs_pw_stream =
obs_pipewire_connect_stream(capture->obs_pw, capture->source, capture->pipewire_node, &connect_info);
}
static void open_pipewire_remote(struct screencast_portal_capture *capture)
{
GVariantBuilder builder;
g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT);
g_dbus_proxy_call_with_unix_fd_list(get_screencast_portal_proxy(), "OpenPipeWireRemote",
g_variant_new("(oa{sv})", capture->session_handle, &builder),
G_DBUS_CALL_FLAGS_NONE, -1, NULL, capture->cancellable,
on_pipewire_remote_opened_cb, capture);
}
/* ------------------------------------------------- */
static void on_start_response_received_cb(GVariant *parameters, void *user_data)
{
struct screencast_portal_capture *capture = user_data;
g_autoptr(GVariant) stream_properties = NULL;
g_autoptr(GVariant) streams = NULL;
g_autoptr(GVariant) result = NULL;
GVariantIter iter;
uint32_t response;
size_t n_streams;
g_variant_get(parameters, "(u@a{sv})", &response, &result);
if (response != 0) {
blog(LOG_WARNING, "[pipewire] Failed to start screencast, denied or cancelled by user");
return;
}
streams = g_variant_lookup_value(result, "streams", G_VARIANT_TYPE_ARRAY);
g_variant_iter_init(&iter, streams);
n_streams = g_variant_iter_n_children(&iter);
if (n_streams != 1) {
blog(LOG_WARNING, "[pipewire] Received more than one stream when only one was expected. "
"This is probably a bug in the desktop portal implementation you are "
"using.");
// The KDE Desktop portal implementation sometimes sends an invalid
// response where more than one stream is attached, and only the
// last one is the one we're looking for. This is the only known
// buggy implementation, so let's at least try to make it work here.
for (size_t i = 0; i < n_streams - 1; i++) {
g_autoptr(GVariant) throwaway_properties = NULL;
uint32_t throwaway_pipewire_node;
g_variant_iter_loop(&iter, "(u@a{sv})", &throwaway_pipewire_node, &throwaway_properties);
}
}
g_variant_iter_loop(&iter, "(u@a{sv})", &capture->pipewire_node, &stream_properties);
if (get_screencast_version() >= 4) {
g_autoptr(GVariant) restore_token = NULL;
g_clear_pointer(&capture->restore_token, bfree);
restore_token = g_variant_lookup_value(result, "restore_token", G_VARIANT_TYPE_STRING);
if (restore_token)
capture->restore_token = bstrdup(g_variant_get_string(restore_token, NULL));
obs_source_save(capture->source);
}
blog(LOG_INFO, "[pipewire] source selected, setting up screencast");
open_pipewire_remote(capture);
}
static void on_started_cb(GObject *source, GAsyncResult *res, void *user_data)
{
UNUSED_PARAMETER(user_data);
g_autoptr(GVariant) result = NULL;
g_autoptr(GError) error = NULL;
result = g_dbus_proxy_call_finish(G_DBUS_PROXY(source), res, &error);
if (error) {
if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
blog(LOG_ERROR, "[pipewire] Error selecting screencast source: %s", error->message);
return;
}
}
static void start(struct screencast_portal_capture *capture)
{
GVariantBuilder builder;
char *request_token;
char *request_path;
portal_create_request_path(&request_path, &request_token);
blog(LOG_INFO, "[pipewire] Asking for %s", capture_type_to_string(capture->capture_type));
portal_signal_subscribe(request_path, capture->cancellable, on_start_response_received_cb, capture);
g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT);
g_variant_builder_add(&builder, "{sv}", "handle_token", g_variant_new_string(request_token));
g_dbus_proxy_call(get_screencast_portal_proxy(), "Start",
g_variant_new("(osa{sv})", capture->session_handle, "", &builder), G_DBUS_CALL_FLAGS_NONE, -1,
capture->cancellable, on_started_cb, NULL);
bfree(request_token);
bfree(request_path);
}
/* ------------------------------------------------- */
static void on_select_source_response_received_cb(GVariant *parameters, void *user_data)
{
struct screencast_portal_capture *capture = user_data;
g_autoptr(GVariant) ret = NULL;
uint32_t response;
blog(LOG_DEBUG, "[pipewire] Response to select source received");
g_variant_get(parameters, "(u@a{sv})", &response, &ret);
if (response != 0) {
blog(LOG_WARNING, "[pipewire] Failed to select source, denied or cancelled by user");
return;
}
start(capture);
}
static void on_source_selected_cb(GObject *source, GAsyncResult *res, void *user_data)
{
UNUSED_PARAMETER(user_data);
g_autoptr(GVariant) result = NULL;
g_autoptr(GError) error = NULL;
result = g_dbus_proxy_call_finish(G_DBUS_PROXY(source), res, &error);
if (error) {
if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
blog(LOG_ERROR, "[pipewire] Error selecting screencast source: %s", error->message);
return;
}
}
static void select_source(struct screencast_portal_capture *capture)
{
GVariantBuilder builder;
uint32_t available_cursor_modes;
char *request_token;
char *request_path;
portal_create_request_path(&request_path, &request_token);
portal_signal_subscribe(request_path, capture->cancellable, on_select_source_response_received_cb, capture);
g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT);
g_variant_builder_add(&builder, "{sv}", "types", g_variant_new_uint32(capture->capture_type));
g_variant_builder_add(&builder, "{sv}", "multiple", g_variant_new_boolean(FALSE));
g_variant_builder_add(&builder, "{sv}", "handle_token", g_variant_new_string(request_token));
available_cursor_modes = get_available_cursor_modes();
if (available_cursor_modes & PORTAL_CURSOR_MODE_METADATA)
g_variant_builder_add(&builder, "{sv}", "cursor_mode",
g_variant_new_uint32(PORTAL_CURSOR_MODE_METADATA));
else if ((available_cursor_modes & PORTAL_CURSOR_MODE_EMBEDDED) && capture->cursor_visible)
g_variant_builder_add(&builder, "{sv}", "cursor_mode",
g_variant_new_uint32(PORTAL_CURSOR_MODE_EMBEDDED));
else
g_variant_builder_add(&builder, "{sv}", "cursor_mode", g_variant_new_uint32(PORTAL_CURSOR_MODE_HIDDEN));
if (get_screencast_version() >= 4) {
g_variant_builder_add(&builder, "{sv}", "persist_mode", g_variant_new_uint32(2));
if (capture->restore_token && *capture->restore_token) {
g_variant_builder_add(&builder, "{sv}", "restore_token",
g_variant_new_string(capture->restore_token));
}
}
g_dbus_proxy_call(get_screencast_portal_proxy(), "SelectSources",
g_variant_new("(oa{sv})", capture->session_handle, &builder), G_DBUS_CALL_FLAGS_NONE, -1,
capture->cancellable, on_source_selected_cb, NULL);
bfree(request_token);
bfree(request_path);
}
/* ------------------------------------------------- */
static void on_create_session_response_received_cb(GVariant *parameters, void *user_data)
{
struct screencast_portal_capture *capture = user_data;
g_autoptr(GVariant) session_handle_variant = NULL;
g_autoptr(GVariant) result = NULL;
uint32_t response;
g_variant_get(parameters, "(u@a{sv})", &response, &result);
if (response != 0) {
blog(LOG_WARNING, "[pipewire] Failed to create session, denied or cancelled by user");
return;
}
blog(LOG_INFO, "[pipewire] Screencast session created");
session_handle_variant = g_variant_lookup_value(result, "session_handle", NULL);
capture->session_handle = g_variant_dup_string(session_handle_variant, NULL);
select_source(capture);
}
static void on_session_created_cb(GObject *source, GAsyncResult *res, void *user_data)
{
UNUSED_PARAMETER(user_data);
g_autoptr(GVariant) result = NULL;
g_autoptr(GError) error = NULL;
result = g_dbus_proxy_call_finish(G_DBUS_PROXY(source), res, &error);
if (error) {
if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
blog(LOG_ERROR, "[pipewire] Error creating screencast session: %s", error->message);
return;
}
}
static void create_session(struct screencast_portal_capture *capture)
{
GVariantBuilder builder;
char *session_token;
char *request_token;
char *request_path;
portal_create_request_path(&request_path, &request_token);
portal_create_session_path(NULL, &session_token);
portal_signal_subscribe(request_path, capture->cancellable, on_create_session_response_received_cb, capture);
g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT);
g_variant_builder_add(&builder, "{sv}", "handle_token", g_variant_new_string(request_token));
g_variant_builder_add(&builder, "{sv}", "session_handle_token", g_variant_new_string(session_token));
g_dbus_proxy_call(get_screencast_portal_proxy(), "CreateSession", g_variant_new("(a{sv})", &builder),
G_DBUS_CALL_FLAGS_NONE, -1, capture->cancellable, on_session_created_cb, NULL);
bfree(session_token);
bfree(request_token);
bfree(request_path);
}
/* ------------------------------------------------- */
static gboolean init_screencast_capture(struct screencast_portal_capture *capture)
{
GDBusConnection *connection;
GDBusProxy *proxy;
capture->cancellable = g_cancellable_new();
connection = portal_get_dbus_connection();
if (!connection)
return FALSE;
proxy = get_screencast_portal_proxy();
if (!proxy)
return FALSE;
blog(LOG_INFO, "PipeWire initialized");
create_session(capture);
return TRUE;
}
static bool reload_session_cb(obs_properties_t *properties, obs_property_t *property, void *data)
{
UNUSED_PARAMETER(properties);
UNUSED_PARAMETER(property);
struct screencast_portal_capture *capture = data;
g_clear_pointer(&capture->restore_token, bfree);
g_clear_pointer(&capture->obs_pw_stream, obs_pipewire_stream_destroy);
g_clear_pointer(&capture->obs_pw, obs_pipewire_destroy);
if (capture->session_handle) {
blog(LOG_DEBUG, "[pipewire] Cleaning previous session %s", capture->session_handle);
g_dbus_connection_call(portal_get_dbus_connection(), "org.freedesktop.portal.Desktop",
capture->session_handle, "org.freedesktop.portal.Session", "Close", NULL, NULL,
G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL);
g_clear_pointer(&capture->session_handle, g_free);
}
init_screencast_capture(capture);
return false;
}
/* obs_source_info methods */
static const char *screencast_portal_desktop_capture_get_name(void *data)
{
UNUSED_PARAMETER(data);
return obs_module_text("PipeWireDesktopCapture");
}
static const char *screencast_portal_window_capture_get_name(void *data)
{
UNUSED_PARAMETER(data);
return obs_module_text("PipeWireWindowCapture");
}
static void *screencast_portal_desktop_capture_create(obs_data_t *settings, obs_source_t *source)
{
struct screencast_portal_capture *capture;
capture = bzalloc(sizeof(struct screencast_portal_capture));
capture->capture_type = OBS_PORTAL_CAPTURE_TYPE_MONITOR;
capture->cursor_visible = obs_data_get_bool(settings, "ShowCursor");
capture->restore_token = bstrdup(obs_data_get_string(settings, "RestoreToken"));
capture->source = source;
init_screencast_capture(capture);
return capture;
}
static void *screencast_portal_window_capture_create(obs_data_t *settings, obs_source_t *source)
{
struct screencast_portal_capture *capture;
capture = bzalloc(sizeof(struct screencast_portal_capture));
capture->capture_type = OBS_PORTAL_CAPTURE_TYPE_WINDOW;
capture->cursor_visible = obs_data_get_bool(settings, "ShowCursor");
capture->restore_token = bstrdup(obs_data_get_string(settings, "RestoreToken"));
capture->source = source;
init_screencast_capture(capture);
return capture;
}
static void *screencast_portal_capture_create(obs_data_t *settings, obs_source_t *source)
{
struct screencast_portal_capture *capture;
capture = bzalloc(sizeof(struct screencast_portal_capture));
capture->capture_type = OBS_PORTAL_CAPTURE_TYPE_UNIFIED;
capture->cursor_visible = obs_data_get_bool(settings, "ShowCursor");
capture->restore_token = bstrdup(obs_data_get_string(settings, "RestoreToken"));
capture->source = source;
init_screencast_capture(capture);
return capture;
}
static void screencast_portal_capture_destroy(void *data)
{
struct screencast_portal_capture *capture = data;
if (!capture)
return;
if (capture->session_handle) {
g_dbus_connection_call(portal_get_dbus_connection(), "org.freedesktop.portal.Desktop",
capture->session_handle, "org.freedesktop.portal.Session", "Close", NULL, NULL,
G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL);
g_clear_pointer(&capture->session_handle, g_free);
}
g_clear_pointer(&capture->restore_token, bfree);
g_clear_pointer(&capture->obs_pw_stream, obs_pipewire_stream_destroy);
obs_pipewire_destroy(capture->obs_pw);
g_cancellable_cancel(capture->cancellable);
g_clear_object(&capture->cancellable);
bfree(capture);
}
static void screencast_portal_capture_save(void *data, obs_data_t *settings)
{
struct screencast_portal_capture *capture = data;
obs_data_set_string(settings, "RestoreToken", capture->restore_token);
}
static void screencast_portal_capture_get_defaults(obs_data_t *settings)
{
obs_data_set_default_bool(settings, "ShowCursor", true);
obs_data_set_default_string(settings, "RestoreToken", NULL);
}
static obs_properties_t *screencast_portal_capture_get_properties(void *data)
{
struct screencast_portal_capture *capture = data;
const char *reload_string_id;
obs_properties_t *properties;
switch (capture->capture_type) {
case OBS_PORTAL_CAPTURE_TYPE_MONITOR:
reload_string_id = "PipeWireSelectMonitor";
break;
case OBS_PORTAL_CAPTURE_TYPE_WINDOW:
reload_string_id = "PipeWireSelectWindow";
break;
case OBS_PORTAL_CAPTURE_TYPE_UNIFIED:
reload_string_id = "PipeWireSelectScreenCast";
break;
default:
return NULL;
}
properties = obs_properties_create();
obs_properties_add_button2(properties, "Reload", obs_module_text(reload_string_id), reload_session_cb, capture);
obs_properties_add_bool(properties, "ShowCursor", obs_module_text("ShowCursor"));
return properties;
}
static void screencast_portal_capture_update(void *data, obs_data_t *settings)
{
struct screencast_portal_capture *capture = data;
capture->cursor_visible = obs_data_get_bool(settings, "ShowCursor");
if (capture->obs_pw_stream)
obs_pipewire_stream_set_cursor_visible(capture->obs_pw_stream, capture->cursor_visible);
}
static void screencast_portal_capture_show(void *data)
{
struct screencast_portal_capture *capture = data;
if (capture->obs_pw_stream)
obs_pipewire_stream_show(capture->obs_pw_stream);
}
static void screencast_portal_capture_hide(void *data)
{
struct screencast_portal_capture *capture = data;
if (capture->obs_pw_stream)
obs_pipewire_stream_hide(capture->obs_pw_stream);
}
static uint32_t screencast_portal_capture_get_width(void *data)
{
struct screencast_portal_capture *capture = data;
if (capture->obs_pw_stream)
return obs_pipewire_stream_get_width(capture->obs_pw_stream);
else
return 0;
}
static uint32_t screencast_portal_capture_get_height(void *data)
{
struct screencast_portal_capture *capture = data;
if (capture->obs_pw_stream)
return obs_pipewire_stream_get_height(capture->obs_pw_stream);
else
return 0;
}
static void screencast_portal_capture_video_render(void *data, gs_effect_t *effect)
{
struct screencast_portal_capture *capture = data;
if (capture->obs_pw_stream)
obs_pipewire_stream_video_render(capture->obs_pw_stream, effect);
}
void screencast_portal_load(void)
{
uint32_t available_capture_types = get_available_capture_types();
bool desktop_capture_available = (available_capture_types & PORTAL_CAPTURE_TYPE_MONITOR) != 0;
bool window_capture_available = (available_capture_types & PORTAL_CAPTURE_TYPE_WINDOW) != 0;
if (available_capture_types == 0) {
blog(LOG_INFO, "[pipewire] No capture sources available");
return;
}
blog(LOG_INFO, "[pipewire] Available capture sources:");
if (desktop_capture_available)
blog(LOG_INFO, "[pipewire] - Monitor source");
if (window_capture_available)
blog(LOG_INFO, "[pipewire] - Window source");
// Desktop capture
const struct obs_source_info screencast_portal_desktop_capture_info = {
.id = "pipewire-desktop-capture-source",
.type = OBS_SOURCE_TYPE_INPUT,
.output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CAP_OBSOLETE,
.get_name = screencast_portal_desktop_capture_get_name,
.create = screencast_portal_desktop_capture_create,
.destroy = screencast_portal_capture_destroy,
.save = screencast_portal_capture_save,
.get_defaults = screencast_portal_capture_get_defaults,
.get_properties = screencast_portal_capture_get_properties,
.update = screencast_portal_capture_update,
.show = screencast_portal_capture_show,
.hide = screencast_portal_capture_hide,
.get_width = screencast_portal_capture_get_width,
.get_height = screencast_portal_capture_get_height,
.video_render = screencast_portal_capture_video_render,
.icon_type = OBS_ICON_TYPE_DESKTOP_CAPTURE,
};
if (desktop_capture_available)
obs_register_source(&screencast_portal_desktop_capture_info);
// Window capture
const struct obs_source_info screencast_portal_window_capture_info = {
.id = "pipewire-window-capture-source",
.type = OBS_SOURCE_TYPE_INPUT,
.output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CAP_OBSOLETE,
.get_name = screencast_portal_window_capture_get_name,
.create = screencast_portal_window_capture_create,
.destroy = screencast_portal_capture_destroy,
.save = screencast_portal_capture_save,
.get_defaults = screencast_portal_capture_get_defaults,
.get_properties = screencast_portal_capture_get_properties,
.update = screencast_portal_capture_update,
.show = screencast_portal_capture_show,
.hide = screencast_portal_capture_hide,
.get_width = screencast_portal_capture_get_width,
.get_height = screencast_portal_capture_get_height,
.video_render = screencast_portal_capture_video_render,
.icon_type = OBS_ICON_TYPE_WINDOW_CAPTURE,
};
if (window_capture_available)
obs_register_source(&screencast_portal_window_capture_info);
// Screen capture (monitor and window)
const struct obs_source_info screencast_portal_capture_info = {
.id = "pipewire-screen-capture-source",
.type = OBS_SOURCE_TYPE_INPUT,
.output_flags = OBS_SOURCE_VIDEO,
.get_name = screencast_portal_desktop_capture_get_name,
.create = screencast_portal_capture_create,
.destroy = screencast_portal_capture_destroy,
.save = screencast_portal_capture_save,
.get_defaults = screencast_portal_capture_get_defaults,
.get_properties = screencast_portal_capture_get_properties,
.update = screencast_portal_capture_update,
.show = screencast_portal_capture_show,
.hide = screencast_portal_capture_hide,
.get_width = screencast_portal_capture_get_width,
.get_height = screencast_portal_capture_get_height,
.video_render = screencast_portal_capture_video_render,
.icon_type = OBS_ICON_TYPE_DESKTOP_CAPTURE,
};
obs_register_source(&screencast_portal_capture_info);
}
void screencast_portal_unload(void)
{
g_clear_object(&screencast_proxy);
}
| 24,327 |
C
|
.c
| 595 | 38.30084 | 113 | 0.73866 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,533 |
screencast-portal.h
|
obsproject_obs-studio/plugins/linux-pipewire/screencast-portal.h
|
/* screencast-portal.h
*
* Copyright 2022 Georges Basile Stavracas Neto <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#pragma once
void screencast_portal_load(void);
void screencast_portal_unload(void);
| 892 |
C
|
.c
| 22 | 38.636364 | 77 | 0.768433 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,535 |
portal.c
|
obsproject_obs-studio/plugins/linux-pipewire/portal.c
|
/* portal.c
*
* Copyright 2021 Georges Basile Stavracas Neto <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "portal.h"
#include "pipewire.h"
#include <util/dstr.h>
struct portal_signal_call {
GCancellable *cancellable;
portal_signal_callback callback;
gpointer user_data;
char *request_path;
guint signal_id;
gulong cancelled_id;
};
#define REQUEST_PATH "/org/freedesktop/portal/desktop/request/%s/obs%u"
#define SESSION_PATH "/org/freedesktop/portal/desktop/session/%s/obs%u"
static GDBusConnection *connection = NULL;
static void ensure_connection(void)
{
g_autoptr(GError) error = NULL;
if (!connection) {
connection = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &error);
if (error) {
blog(LOG_WARNING, "[portals] Error retrieving D-Bus connection: %s", error->message);
return;
}
}
}
char *get_sender_name(void)
{
char *sender_name;
char *aux;
ensure_connection();
sender_name = bstrdup(g_dbus_connection_get_unique_name(connection) + 1);
/* Replace dots by underscores */
while ((aux = strstr(sender_name, ".")) != NULL)
*aux = '_';
return sender_name;
}
GDBusConnection *portal_get_dbus_connection(void)
{
ensure_connection();
return connection;
}
void portal_create_request_path(char **out_path, char **out_token)
{
static uint32_t request_token_count = 0;
request_token_count++;
if (out_token) {
struct dstr str;
dstr_init(&str);
dstr_printf(&str, "obs%u", request_token_count);
*out_token = str.array;
}
if (out_path) {
char *sender_name;
struct dstr str;
sender_name = get_sender_name();
dstr_init(&str);
dstr_printf(&str, REQUEST_PATH, sender_name, request_token_count);
*out_path = str.array;
bfree(sender_name);
}
}
void portal_create_session_path(char **out_path, char **out_token)
{
static uint32_t session_token_count = 0;
session_token_count++;
if (out_token) {
struct dstr str;
dstr_init(&str);
dstr_printf(&str, "obs%u", session_token_count);
*out_token = str.array;
}
if (out_path) {
char *sender_name;
struct dstr str;
sender_name = get_sender_name();
dstr_init(&str);
dstr_printf(&str, SESSION_PATH, sender_name, session_token_count);
*out_path = str.array;
bfree(sender_name);
}
}
static void portal_signal_call_free(struct portal_signal_call *call)
{
if (call->signal_id)
g_dbus_connection_signal_unsubscribe(portal_get_dbus_connection(), call->signal_id);
if (call->cancelled_id > 0)
g_signal_handler_disconnect(call->cancellable, call->cancelled_id);
g_clear_pointer(&call->request_path, bfree);
bfree(call);
}
static void on_cancelled_cb(GCancellable *cancellable, void *data)
{
UNUSED_PARAMETER(cancellable);
struct portal_signal_call *call = data;
blog(LOG_INFO, "[portals] Request cancelled");
g_dbus_connection_call(portal_get_dbus_connection(), "org.freedesktop.portal.Desktop", call->request_path,
"org.freedesktop.portal.Request", "Close", NULL, NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL,
NULL, NULL);
portal_signal_call_free(call);
}
static void on_response_received_cb(GDBusConnection *connection, const char *sender_name, const char *object_path,
const char *interface_name, const char *signal_name, GVariant *parameters,
void *user_data)
{
UNUSED_PARAMETER(connection);
UNUSED_PARAMETER(sender_name);
UNUSED_PARAMETER(object_path);
UNUSED_PARAMETER(interface_name);
UNUSED_PARAMETER(signal_name);
struct portal_signal_call *call = user_data;
if (call->callback)
call->callback(parameters, call->user_data);
portal_signal_call_free(call);
}
void portal_signal_subscribe(const char *path, GCancellable *cancellable, portal_signal_callback callback,
gpointer user_data)
{
struct portal_signal_call *call;
call = bzalloc(sizeof(struct portal_signal_call));
call->request_path = bstrdup(path);
call->callback = callback;
call->user_data = user_data;
call->cancellable = cancellable ? g_object_ref(cancellable) : NULL;
call->cancelled_id = cancellable ? g_signal_connect(cancellable, "cancelled", G_CALLBACK(on_cancelled_cb), call)
: 0;
call->signal_id = g_dbus_connection_signal_subscribe(
portal_get_dbus_connection(), "org.freedesktop.portal.Desktop", "org.freedesktop.portal.Request",
"Response", call->request_path, NULL, G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE, on_response_received_cb, call,
NULL);
}
| 5,039 |
C
|
.c
| 149 | 31.248322 | 114 | 0.737059 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,544 |
transition-fade.c
|
obsproject_obs-studio/plugins/obs-transitions/transition-fade.c
|
#include <obs-module.h>
struct fade_info {
obs_source_t *source;
gs_effect_t *effect;
gs_eparam_t *a_param;
gs_eparam_t *b_param;
gs_eparam_t *fade_param;
};
static const char *fade_get_name(void *type_data)
{
UNUSED_PARAMETER(type_data);
return obs_module_text("FadeTransition");
}
static void *fade_create(obs_data_t *settings, obs_source_t *source)
{
struct fade_info *fade;
char *file = obs_module_file("fade_transition.effect");
gs_effect_t *effect;
obs_enter_graphics();
effect = gs_effect_create_from_file(file, NULL);
obs_leave_graphics();
bfree(file);
if (!effect) {
blog(LOG_ERROR, "Could not find fade_transition.effect");
return NULL;
}
fade = bmalloc(sizeof(*fade));
fade->source = source;
fade->effect = effect;
fade->a_param = gs_effect_get_param_by_name(effect, "tex_a");
fade->b_param = gs_effect_get_param_by_name(effect, "tex_b");
fade->fade_param = gs_effect_get_param_by_name(effect, "fade_val");
UNUSED_PARAMETER(settings);
return fade;
}
static void fade_destroy(void *data)
{
struct fade_info *fade = data;
bfree(fade);
}
static void fade_callback(void *data, gs_texture_t *a, gs_texture_t *b, float t, uint32_t cx, uint32_t cy)
{
if (a || b) {
struct fade_info *fade = data;
const bool previous = gs_framebuffer_srgb_enabled();
gs_enable_framebuffer_srgb(true);
const char *tech_name = "Fade";
if (!a || !b) {
tech_name = "FadeSingle";
if (a) {
gs_effect_set_texture_srgb(fade->a_param, a);
t = 1.f - t;
} else {
gs_effect_set_texture_srgb(fade->a_param, b);
}
} else {
/* texture setters look reversed, but they aren't */
if (gs_get_color_space() == GS_CS_SRGB) {
/* users want nonlinear fade */
gs_effect_set_texture(fade->a_param, a);
gs_effect_set_texture(fade->b_param, b);
} else {
/* nonlinear fade is too wrong, so use linear fade */
gs_effect_set_texture_srgb(fade->a_param, a);
gs_effect_set_texture_srgb(fade->b_param, b);
tech_name = "FadeLinear";
}
}
gs_effect_set_float(fade->fade_param, t);
while (gs_effect_loop(fade->effect, tech_name))
gs_draw_sprite(NULL, 0, cx, cy);
gs_enable_framebuffer_srgb(previous);
}
}
static void fade_video_render(void *data, gs_effect_t *effect)
{
UNUSED_PARAMETER(effect);
const bool previous = gs_set_linear_srgb(true);
struct fade_info *fade = data;
obs_transition_video_render2(fade->source, fade_callback, NULL);
gs_set_linear_srgb(previous);
}
static float mix_a(void *data, float t)
{
UNUSED_PARAMETER(data);
return 1.0f - t;
}
static float mix_b(void *data, float t)
{
UNUSED_PARAMETER(data);
return t;
}
static bool fade_audio_render(void *data, uint64_t *ts_out, struct obs_source_audio_mix *audio, uint32_t mixers,
size_t channels, size_t sample_rate)
{
struct fade_info *fade = data;
return obs_transition_audio_render(fade->source, ts_out, audio, mixers, channels, sample_rate, mix_a, mix_b);
}
static enum gs_color_space fade_video_get_color_space(void *data, size_t count,
const enum gs_color_space *preferred_spaces)
{
struct fade_info *const fade = data;
const enum gs_color_space transition_space = obs_transition_video_get_color_space(fade->source);
enum gs_color_space space = transition_space;
for (size_t i = 0; i < count; ++i) {
space = preferred_spaces[i];
if (space == transition_space)
break;
}
return space;
}
struct obs_source_info fade_transition = {
.id = "fade_transition",
.type = OBS_SOURCE_TYPE_TRANSITION,
.get_name = fade_get_name,
.create = fade_create,
.destroy = fade_destroy,
.video_render = fade_video_render,
.audio_render = fade_audio_render,
.video_get_color_space = fade_video_get_color_space,
};
| 3,712 |
C
|
.c
| 121 | 28.033058 | 112 | 0.699495 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,591 |
audio-helpers.c
|
obsproject_obs-studio/plugins/win-capture/audio-helpers.c
|
#include "audio-helpers.h"
#include <util/dstr.h>
static inline bool settings_changed(obs_data_t *old_settings, obs_data_t *new_settings)
{
const char *old_window = obs_data_get_string(old_settings, "window");
const char *new_window = obs_data_get_string(new_settings, "window");
enum window_priority old_priority = obs_data_get_int(old_settings, "priority");
enum window_priority new_priority = obs_data_get_int(new_settings, "priority");
// Changes to priority only matter if a window is set
return (old_priority != new_priority && *new_window) || strcmp(old_window, new_window) != 0;
}
static inline void reroute_wasapi_source(obs_source_t *wasapi, obs_source_t *target)
{
proc_handler_t *ph = obs_source_get_proc_handler(wasapi);
calldata_t cd = {0};
calldata_set_ptr(&cd, "target", target);
proc_handler_call(ph, "reroute_audio", &cd);
calldata_free(&cd);
}
void setup_audio_source(obs_source_t *parent, obs_source_t **child, const char *window, bool enabled,
enum window_priority priority)
{
if (enabled) {
obs_data_t *wasapi_settings = NULL;
if (window) {
wasapi_settings = obs_data_create();
obs_data_set_string(wasapi_settings, "window", window);
obs_data_set_int(wasapi_settings, "priority", priority);
}
if (!*child) {
struct dstr name = {0};
dstr_printf(&name, "%s (%s)", obs_source_get_name(parent), TEXT_CAPTURE_AUDIO_SUFFIX);
*child = obs_source_create_private(AUDIO_SOURCE_TYPE, name.array, wasapi_settings);
// Ensure child gets activated/deactivated properly
obs_source_add_active_child(parent, *child);
// Reroute audio to come from window/game capture source
reroute_wasapi_source(*child, parent);
// Show source in mixer
obs_source_set_audio_active(parent, true);
dstr_free(&name);
} else if (wasapi_settings) {
obs_data_t *old_settings = obs_source_get_settings(*child);
// Only bother updating if settings changed
if (settings_changed(old_settings, wasapi_settings))
obs_source_update(*child, wasapi_settings);
obs_data_release(old_settings);
}
obs_data_release(wasapi_settings);
} else {
obs_source_set_audio_active(parent, false);
if (*child) {
reroute_wasapi_source(*child, NULL);
obs_source_remove_active_child(parent, *child);
obs_source_release(*child);
*child = NULL;
}
}
}
static inline void encode_dstr(struct dstr *str)
{
dstr_replace(str, "#", "#22");
dstr_replace(str, ":", "#3A");
}
void reconfigure_audio_source(obs_source_t *source, HWND window)
{
struct dstr title = {0};
struct dstr class = {0};
struct dstr exe = {0};
struct dstr encoded = {0};
ms_get_window_title(&title, window);
ms_get_window_class(&class, window);
ms_get_window_exe(&exe, window);
encode_dstr(&title);
encode_dstr(&class);
encode_dstr(&exe);
dstr_cat_dstr(&encoded, &title);
dstr_cat(&encoded, ":");
dstr_cat_dstr(&encoded, &class);
dstr_cat(&encoded, ":");
dstr_cat_dstr(&encoded, &exe);
obs_data_t *audio_settings = obs_data_create();
obs_data_set_string(audio_settings, "window", encoded.array);
obs_data_set_int(audio_settings, "priority", WINDOW_PRIORITY_CLASS);
obs_source_update(source, audio_settings);
obs_data_release(audio_settings);
dstr_free(&encoded);
dstr_free(&title);
dstr_free(&class);
dstr_free(&exe);
}
void rename_audio_source(void *param, calldata_t *data)
{
obs_source_t *src = *(obs_source_t **)param;
if (!src)
return;
struct dstr name = {0};
dstr_printf(&name, "%s (%s)", calldata_string(data, "new_name"), TEXT_CAPTURE_AUDIO_SUFFIX);
obs_source_set_name(src, name.array);
dstr_free(&name);
}
| 3,594 |
C
|
.c
| 100 | 33.31 | 101 | 0.710003 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,666 |
nvenc-internal.h
|
obsproject_obs-studio/plugins/obs-nvenc/nvenc-internal.h
|
#pragma once
#include "cuda-helpers.h"
#include "nvenc-helpers.h"
#include <util/deque.h>
#include <opts-parser.h>
#ifdef _WIN32
#define INITGUID
#include <dxgi.h>
#include <d3d11.h>
#include <d3d11_1.h>
#else
#include <glad/glad.h>
#endif
#define do_log(level, format, ...) \
blog(level, "[obs-nvenc: '%s'] " format, obs_encoder_get_name(enc->encoder), ##__VA_ARGS__)
#define error(format, ...) do_log(LOG_ERROR, format, ##__VA_ARGS__)
#define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
#define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
#define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
#define error_hr(msg) error("%s: %s: 0x%08lX", __FUNCTION__, msg, (uint32_t)hr);
#define NV_FAIL(format, ...) nv_fail(enc->encoder, format, ##__VA_ARGS__)
#define NV_FAILED(x) nv_failed(enc->encoder, x, __FUNCTION__, #x)
/* ------------------------------------------------------------------------- */
/* Main Implementation Structure */
struct nvenc_properties {
int64_t bitrate;
int64_t max_bitrate;
int64_t keyint_sec;
int64_t cqp;
int64_t device;
int64_t bf;
int64_t bframe_ref_mode;
int64_t split_encode;
int64_t target_quality;
const char *rate_control;
const char *preset;
const char *profile;
const char *tune;
const char *multipass;
const char *opts_str;
bool adaptive_quantization;
bool lookahead;
bool disable_scenecut;
bool repeat_headers;
bool force_cuda_tex;
struct obs_options opts;
obs_data_t *data;
};
struct nvenc_data {
obs_encoder_t *encoder;
enum codec_type codec;
GUID codec_guid;
void *session;
NV_ENC_INITIALIZE_PARAMS params;
NV_ENC_CONFIG config;
uint32_t buf_count;
int output_delay;
int buffers_queued;
size_t next_bitstream;
size_t cur_bitstream;
bool encode_started;
bool first_packet;
bool can_change_bitrate;
bool non_texture;
DARRAY(struct handle_tex) input_textures;
DARRAY(struct nv_bitstream) bitstreams;
DARRAY(struct nv_cuda_surface) surfaces;
NV_ENC_BUFFER_FORMAT surface_format;
struct deque dts_list;
DARRAY(uint8_t) packet_data;
int64_t packet_pts;
bool packet_keyframe;
#ifdef _WIN32
DARRAY(struct nv_texture) textures;
ID3D11Device *device;
ID3D11DeviceContext *context;
#endif
uint32_t cx;
uint32_t cy;
enum video_format in_format;
uint8_t *header;
size_t header_size;
uint8_t *sei;
size_t sei_size;
int8_t *roi_map;
size_t roi_map_size;
uint32_t roi_increment;
struct nvenc_properties props;
CUcontext cu_ctx;
};
/* ------------------------------------------------------------------------- */
/* Resource data structures */
/* Input texture handles */
struct handle_tex {
#ifdef _WIN32
uint32_t handle;
ID3D11Texture2D *tex;
IDXGIKeyedMutex *km;
#else
GLuint tex_id;
/* CUDA mappings */
CUgraphicsResource res_y;
CUgraphicsResource res_uv;
#endif
};
/* Bitstream buffer */
struct nv_bitstream {
void *ptr;
};
/** Mapped resources **/
/* CUDA Arrays */
struct nv_cuda_surface {
CUarray tex;
NV_ENC_REGISTERED_PTR res;
NV_ENC_INPUT_PTR *mapped_res;
};
#ifdef _WIN32
/* DX11 textures */
struct nv_texture {
void *res;
ID3D11Texture2D *tex;
void *mapped_res;
};
#endif
/* ------------------------------------------------------------------------- */
/* Shared functions */
bool nvenc_encode_base(struct nvenc_data *enc, struct nv_bitstream *bs, void *pic, int64_t pts,
struct encoder_packet *packet, bool *received_packet);
/* ------------------------------------------------------------------------- */
/* Backend-specific functions */
#ifdef _WIN32
/** D3D11 **/
bool d3d11_init(struct nvenc_data *enc, obs_data_t *settings);
void d3d11_free(struct nvenc_data *enc);
bool d3d11_init_textures(struct nvenc_data *enc);
void d3d11_free_textures(struct nvenc_data *enc);
bool d3d11_encode(void *data, struct encoder_texture *texture, int64_t pts, uint64_t lock_key, uint64_t *next_key,
struct encoder_packet *packet, bool *received_packet);
#endif
/** CUDA **/
bool cuda_ctx_init(struct nvenc_data *enc, obs_data_t *settings, bool texture);
void cuda_ctx_free(struct nvenc_data *enc);
bool cuda_init_surfaces(struct nvenc_data *enc);
void cuda_free_surfaces(struct nvenc_data *enc);
bool cuda_encode(void *data, struct encoder_frame *frame, struct encoder_packet *packet, bool *received_packet);
#ifndef _WIN32
/** CUDA OpenGL **/
void cuda_opengl_free(struct nvenc_data *enc);
bool cuda_opengl_encode(void *data, struct encoder_texture *tex, int64_t pts, uint64_t lock_key, uint64_t *next_key,
struct encoder_packet *packet, bool *received_packet);
#endif
/* ------------------------------------------------------------------------- */
/* Properties crap */
void nvenc_properties_read(struct nvenc_properties *enc, obs_data_t *settings);
void h264_nvenc_defaults(obs_data_t *settings);
void hevc_nvenc_defaults(obs_data_t *settings);
void av1_nvenc_defaults(obs_data_t *settings);
obs_properties_t *h264_nvenc_properties(void *);
obs_properties_t *hevc_nvenc_properties(void *);
obs_properties_t *av1_nvenc_properties(void *);
/* Custom argument parsing */
void apply_user_args(struct nvenc_data *enc);
bool get_user_arg_int(struct nvenc_data *enc, const char *name, int *val);
| 5,446 |
C
|
.c
| 163 | 31.588957 | 116 | 0.650573 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,667 |
obs-nvenc.h
|
obsproject_obs-studio/plugins/obs-nvenc/obs-nvenc.h
|
#pragma once
#include <util/platform.h>
bool nvenc_supported(void);
void obs_nvenc_load(void);
void obs_nvenc_unload(void);
void obs_cuda_load(void);
void obs_cuda_unload(void);
| 182 |
C
|
.c
| 7 | 24.428571 | 28 | 0.783626 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,669 |
nvenc-compat.c
|
obsproject_obs-studio/plugins/obs-nvenc/nvenc-compat.c
|
#include "nvenc-helpers.h"
#include <util/dstr.h>
/*
* Compatibility encoder objects for pre-31.0 encoder compatibility.
*
* All they do is update the settings object, and then reroute to one of the
* new encoder implementations.
*
* This should be removed once NVENC settings are migrated directly and
* backwards-compatibility is no longer required.
*/
/* ------------------------------------------------------------------------- */
/* Actual redirector implementation. */
static void migrate_settings(obs_data_t *settings)
{
const char *preset = obs_data_get_string(settings, "preset2");
obs_data_set_string(settings, "preset", preset);
obs_data_set_bool(settings, "adaptive_quantization", obs_data_get_bool(settings, "psycho_aq"));
if (obs_data_has_user_value(settings, "gpu") && num_encoder_devices() > 1) {
obs_data_set_int(settings, "device", obs_data_get_int(settings, "gpu"));
}
}
static void *nvenc_reroute(enum codec_type codec, obs_data_t *settings, obs_encoder_t *encoder, bool texture)
{
/* Update settings object to v2 encoder configuration */
migrate_settings(settings);
switch (codec) {
case CODEC_H264:
return obs_encoder_create_rerouted(encoder, texture ? "obs_nvenc_h264_tex" : "obs_nvenc_h264_soft");
case CODEC_HEVC:
return obs_encoder_create_rerouted(encoder, texture ? "obs_nvenc_hevc_tex" : "obs_nvenc_hevc_soft");
case CODEC_AV1:
return obs_encoder_create_rerouted(encoder, texture ? "obs_nvenc_av1_tex" : "obs_nvenc_av1_soft");
}
return NULL;
}
/* ------------------------------------------------------------------------- */
static const char *h264_nvenc_get_name(void *type_data)
{
UNUSED_PARAMETER(type_data);
return "NVIDIA NVENC H.264";
}
#ifdef ENABLE_HEVC
static const char *hevc_nvenc_get_name(void *type_data)
{
UNUSED_PARAMETER(type_data);
return "NVIDIA NVENC HEVC";
}
#endif
static const char *av1_nvenc_get_name(void *type_data)
{
UNUSED_PARAMETER(type_data);
return "NVIDIA NVENC AV1";
}
static void *h264_nvenc_create(obs_data_t *settings, obs_encoder_t *encoder)
{
return nvenc_reroute(CODEC_H264, settings, encoder, true);
}
#ifdef ENABLE_HEVC
static void *hevc_nvenc_create(obs_data_t *settings, obs_encoder_t *encoder)
{
return nvenc_reroute(CODEC_HEVC, settings, encoder, true);
}
#endif
static void *av1_nvenc_create(obs_data_t *settings, obs_encoder_t *encoder)
{
return nvenc_reroute(CODEC_AV1, settings, encoder, true);
}
static void *h264_nvenc_soft_create(obs_data_t *settings, obs_encoder_t *encoder)
{
return nvenc_reroute(CODEC_H264, settings, encoder, false);
}
#ifdef ENABLE_HEVC
static void *hevc_nvenc_soft_create(obs_data_t *settings, obs_encoder_t *encoder)
{
return nvenc_reroute(CODEC_HEVC, settings, encoder, false);
}
#endif
static void *av1_nvenc_soft_create(obs_data_t *settings, obs_encoder_t *encoder)
{
return nvenc_reroute(CODEC_AV1, settings, encoder, false);
}
static void nvenc_defaults_base(enum codec_type codec, obs_data_t *settings)
{
/* Defaults from legacy FFmpeg encoder */
obs_data_set_default_int(settings, "bitrate", 2500);
obs_data_set_default_int(settings, "max_bitrate", 5000);
obs_data_set_default_int(settings, "keyint_sec", 0);
obs_data_set_default_int(settings, "cqp", 20);
obs_data_set_default_string(settings, "rate_control", "CBR");
obs_data_set_default_string(settings, "preset2", "p5");
obs_data_set_default_string(settings, "multipass", "qres");
obs_data_set_default_string(settings, "tune", "hq");
obs_data_set_default_string(settings, "profile", codec != CODEC_H264 ? "main" : "high");
obs_data_set_default_bool(settings, "psycho_aq", true);
obs_data_set_default_int(settings, "gpu", 0);
obs_data_set_default_int(settings, "bf", 2);
obs_data_set_default_bool(settings, "repeat_headers", false);
}
static void h264_nvenc_defaults(obs_data_t *settings)
{
nvenc_defaults_base(CODEC_H264, settings);
}
#ifdef ENABLE_HEVC
static void hevc_nvenc_defaults(obs_data_t *settings)
{
nvenc_defaults_base(CODEC_HEVC, settings);
}
#endif
static void av1_nvenc_defaults(obs_data_t *settings)
{
nvenc_defaults_base(CODEC_AV1, settings);
}
static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p, obs_data_t *settings)
{
const char *rc = obs_data_get_string(settings, "rate_control");
bool cqp = astrcmpi(rc, "CQP") == 0;
bool vbr = astrcmpi(rc, "VBR") == 0;
bool lossless = astrcmpi(rc, "lossless") == 0;
p = obs_properties_get(ppts, "bitrate");
obs_property_set_visible(p, !cqp && !lossless);
p = obs_properties_get(ppts, "max_bitrate");
obs_property_set_visible(p, vbr);
p = obs_properties_get(ppts, "cqp");
obs_property_set_visible(p, cqp);
p = obs_properties_get(ppts, "preset2");
obs_property_set_visible(p, !lossless);
p = obs_properties_get(ppts, "tune");
obs_property_set_visible(p, !lossless);
return true;
}
static obs_properties_t *nvenc_properties_internal(enum codec_type codec)
{
obs_properties_t *props = obs_properties_create();
obs_property_t *p;
p = obs_properties_add_list(props, "rate_control", obs_module_text("RateControl"), OBS_COMBO_TYPE_LIST,
OBS_COMBO_FORMAT_STRING);
obs_property_list_add_string(p, "CBR", "CBR");
obs_property_list_add_string(p, "CQP", "CQP");
obs_property_list_add_string(p, "VBR", "VBR");
obs_property_list_add_string(p, obs_module_text("Lossless"), "lossless");
obs_property_set_modified_callback(p, rate_control_modified);
p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), 50, 300000, 50);
obs_property_int_set_suffix(p, " Kbps");
p = obs_properties_add_int(props, "max_bitrate", obs_module_text("MaxBitrate"), 50, 300000, 50);
obs_property_int_set_suffix(p, " Kbps");
obs_properties_add_int(props, "cqp", obs_module_text("CQLevel"), 1, codec == CODEC_AV1 ? 63 : 51, 1);
p = obs_properties_add_int(props, "keyint_sec", obs_module_text("KeyframeIntervalSec"), 0, 10, 1);
obs_property_int_set_suffix(p, " s");
p = obs_properties_add_list(props, "preset2", obs_module_text("Preset"), OBS_COMBO_TYPE_LIST,
OBS_COMBO_FORMAT_STRING);
#define add_preset(val) obs_property_list_add_string(p, obs_module_text("Preset." val), val)
add_preset("p1");
add_preset("p2");
add_preset("p3");
add_preset("p4");
add_preset("p5");
add_preset("p6");
add_preset("p7");
#undef add_preset
p = obs_properties_add_list(props, "tune", obs_module_text("Tuning"), OBS_COMBO_TYPE_LIST,
OBS_COMBO_FORMAT_STRING);
#define add_tune(val) obs_property_list_add_string(p, obs_module_text("Tuning." val), val)
add_tune("hq");
add_tune("ll");
add_tune("ull");
#undef add_tune
p = obs_properties_add_list(props, "multipass", obs_module_text("Multipass"), OBS_COMBO_TYPE_LIST,
OBS_COMBO_FORMAT_STRING);
#define add_multipass(val) obs_property_list_add_string(p, obs_module_text("Multipass." val), val)
add_multipass("disabled");
add_multipass("qres");
add_multipass("fullres");
#undef add_multipass
p = obs_properties_add_list(props, "profile", obs_module_text("Profile"), OBS_COMBO_TYPE_LIST,
OBS_COMBO_FORMAT_STRING);
#define add_profile(val) obs_property_list_add_string(p, val, val)
if (codec == CODEC_HEVC) {
add_profile("main10");
add_profile("main");
} else if (codec == CODEC_AV1) {
add_profile("main");
} else {
add_profile("high");
add_profile("main");
add_profile("baseline");
}
#undef add_profile
p = obs_properties_add_bool(props, "lookahead", obs_module_text("LookAhead"));
obs_property_set_long_description(p, obs_module_text("LookAhead.ToolTip"));
p = obs_properties_add_bool(props, "repeat_headers", "repeat_headers");
obs_property_set_visible(p, false);
p = obs_properties_add_bool(props, "psycho_aq", obs_module_text("PsychoVisualTuning"));
obs_property_set_long_description(p, obs_module_text("PsychoVisualTuning.ToolTip"));
obs_properties_add_int(props, "gpu", obs_module_text("GPU"), 0, 8, 1);
obs_properties_add_int(props, "bf", obs_module_text("BFrames"), 0, 4, 1);
return props;
}
static obs_properties_t *h264_nvenc_properties(void *unused)
{
UNUSED_PARAMETER(unused);
return nvenc_properties_internal(CODEC_H264);
}
#ifdef ENABLE_HEVC
static obs_properties_t *hevc_nvenc_properties(void *unused)
{
UNUSED_PARAMETER(unused);
return nvenc_properties_internal(CODEC_HEVC);
}
#endif
static obs_properties_t *av1_nvenc_properties(void *unused)
{
UNUSED_PARAMETER(unused);
return nvenc_properties_internal(CODEC_AV1);
}
/* ------------------------------------------------------------------------- */
/* Stubs for required - but unused - functions. */
static void fake_nvenc_destroy(void *p)
{
UNUSED_PARAMETER(p);
}
static bool fake_encode(void *data, struct encoder_frame *frame, struct encoder_packet *packet, bool *received_packet)
{
UNUSED_PARAMETER(data);
UNUSED_PARAMETER(frame);
UNUSED_PARAMETER(packet);
UNUSED_PARAMETER(received_packet);
return true;
}
static bool fake_encode_tex2(void *data, struct encoder_texture *texture, int64_t pts, uint64_t lock_key,
uint64_t *next_key, struct encoder_packet *packet, bool *received_packet)
{
UNUSED_PARAMETER(data);
UNUSED_PARAMETER(texture);
UNUSED_PARAMETER(pts);
UNUSED_PARAMETER(lock_key);
UNUSED_PARAMETER(next_key);
UNUSED_PARAMETER(packet);
UNUSED_PARAMETER(received_packet);
return true;
}
struct obs_encoder_info compat_h264_nvenc_info = {
.id = "jim_nvenc",
.codec = "h264",
.type = OBS_ENCODER_VIDEO,
.caps = OBS_ENCODER_CAP_PASS_TEXTURE | OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI |
OBS_ENCODER_CAP_DEPRECATED,
.get_name = h264_nvenc_get_name,
.create = h264_nvenc_create,
.destroy = fake_nvenc_destroy,
.encode_texture2 = fake_encode_tex2,
.get_defaults = h264_nvenc_defaults,
.get_properties = h264_nvenc_properties,
};
#ifdef ENABLE_HEVC
struct obs_encoder_info compat_hevc_nvenc_info = {
.id = "jim_hevc_nvenc",
.codec = "hevc",
.type = OBS_ENCODER_VIDEO,
.caps = OBS_ENCODER_CAP_PASS_TEXTURE | OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI |
OBS_ENCODER_CAP_DEPRECATED,
.get_name = hevc_nvenc_get_name,
.create = hevc_nvenc_create,
.destroy = fake_nvenc_destroy,
.encode_texture2 = fake_encode_tex2,
.get_defaults = hevc_nvenc_defaults,
.get_properties = hevc_nvenc_properties,
};
#endif
struct obs_encoder_info compat_av1_nvenc_info = {
.id = "jim_av1_nvenc",
.codec = "av1",
.type = OBS_ENCODER_VIDEO,
.caps = OBS_ENCODER_CAP_PASS_TEXTURE | OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI |
OBS_ENCODER_CAP_DEPRECATED,
.get_name = av1_nvenc_get_name,
.create = av1_nvenc_create,
.destroy = fake_nvenc_destroy,
.encode_texture2 = fake_encode_tex2,
.get_defaults = av1_nvenc_defaults,
.get_properties = av1_nvenc_properties,
};
struct obs_encoder_info compat_h264_nvenc_soft_info = {
.id = "obs_nvenc_h264_cuda",
.codec = "h264",
.type = OBS_ENCODER_VIDEO,
.caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI | OBS_ENCODER_CAP_DEPRECATED,
.get_name = h264_nvenc_get_name,
.create = h264_nvenc_soft_create,
.destroy = fake_nvenc_destroy,
.encode = fake_encode,
.get_defaults = h264_nvenc_defaults,
.get_properties = h264_nvenc_properties,
};
#ifdef ENABLE_HEVC
struct obs_encoder_info compat_hevc_nvenc_soft_info = {
.id = "obs_nvenc_hevc_cuda",
.codec = "hevc",
.type = OBS_ENCODER_VIDEO,
.caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI | OBS_ENCODER_CAP_DEPRECATED,
.get_name = hevc_nvenc_get_name,
.create = hevc_nvenc_soft_create,
.destroy = fake_nvenc_destroy,
.encode = fake_encode,
.get_defaults = hevc_nvenc_defaults,
.get_properties = hevc_nvenc_properties,
};
#endif
struct obs_encoder_info compat_av1_nvenc_soft_info = {
.id = "obs_nvenc_av1_cuda",
.codec = "av1",
.type = OBS_ENCODER_VIDEO,
.caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI | OBS_ENCODER_CAP_DEPRECATED,
.get_name = av1_nvenc_get_name,
.create = av1_nvenc_soft_create,
.destroy = fake_nvenc_destroy,
.encode = fake_encode,
.get_defaults = av1_nvenc_defaults,
.get_properties = av1_nvenc_properties,
};
void register_compat_encoders(void)
{
obs_register_encoder(&compat_h264_nvenc_info);
obs_register_encoder(&compat_h264_nvenc_soft_info);
#ifdef ENABLE_HEVC
obs_register_encoder(&compat_hevc_nvenc_info);
obs_register_encoder(&compat_hevc_nvenc_soft_info);
#endif
if (is_codec_supported(CODEC_AV1)) {
obs_register_encoder(&compat_av1_nvenc_info);
obs_register_encoder(&compat_av1_nvenc_soft_info);
}
#ifdef REGISTER_FFMPEG_IDS
compat_h264_nvenc_soft_info.id = "ffmpeg_nvenc";
obs_register_encoder(&compat_h264_nvenc_soft_info);
#ifdef ENABLE_HEVC
compat_hevc_nvenc_soft_info.id = "ffmpeg_hevc_nvenc";
obs_register_encoder(&compat_hevc_nvenc_soft_info);
#endif
#endif
}
| 12,720 |
C
|
.c
| 341 | 35.302053 | 118 | 0.717035 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,670 |
nvenc-properties.c
|
obsproject_obs-studio/plugins/obs-nvenc/nvenc-properties.c
|
#include "nvenc-internal.h"
void nvenc_properties_read(struct nvenc_properties *props, obs_data_t *settings)
{
props->bitrate = obs_data_get_int(settings, "bitrate");
props->max_bitrate = obs_data_get_int(settings, "max_bitrate");
props->keyint_sec = obs_data_get_int(settings, "keyint_sec");
props->cqp = obs_data_get_int(settings, "cqp");
props->device = obs_data_get_int(settings, "device");
props->bf = obs_data_get_int(settings, "bf");
props->bframe_ref_mode = obs_data_get_int(settings, "bframe_ref_mode");
props->split_encode = obs_data_get_int(settings, "split_encode");
props->target_quality = obs_data_get_int(settings, "target_quality");
props->rate_control = obs_data_get_string(settings, "rate_control");
props->preset = obs_data_get_string(settings, "preset");
props->profile = obs_data_get_string(settings, "profile");
props->tune = obs_data_get_string(settings, "tune");
props->multipass = obs_data_get_string(settings, "multipass");
props->adaptive_quantization = obs_data_get_bool(settings, "adaptive_quantization");
props->lookahead = obs_data_get_bool(settings, "lookahead");
props->disable_scenecut = obs_data_get_bool(settings, "disable_scenecut");
props->repeat_headers = obs_data_get_bool(settings, "repeat_headers");
props->force_cuda_tex = obs_data_get_bool(settings, "force_cuda_tex");
if (obs_data_has_user_value(settings, "opts")) {
props->opts_str = obs_data_get_string(settings, "opts");
props->opts = obs_parse_options(props->opts_str);
}
/* Retain settings object until destroyed since we use its strings. */
obs_data_addref(settings);
props->data = settings;
}
static void nvenc_defaults_base(enum codec_type codec, obs_data_t *settings)
{
struct encoder_caps *caps = get_encoder_caps(codec);
obs_data_set_default_int(settings, "bitrate", 10000);
obs_data_set_default_int(settings, "max_bitrate", 10000);
obs_data_set_default_int(settings, "target_quality", 20);
obs_data_set_default_int(settings, "keyint_sec", 0);
obs_data_set_default_int(settings, "cqp", 20);
obs_data_set_default_int(settings, "device", -1);
obs_data_set_default_int(settings, "bf", caps->bframes > 0 ? 2 : 0);
obs_data_set_default_string(settings, "rate_control", "cbr");
obs_data_set_default_string(settings, "preset", "p5");
obs_data_set_default_string(settings, "multipass", "qres");
obs_data_set_default_string(settings, "tune", "hq");
obs_data_set_default_string(settings, "profile", codec != CODEC_H264 ? "main" : "high");
obs_data_set_default_bool(settings, "adaptive_quantization", true);
obs_data_set_default_bool(settings, "lookahead", caps->lookahead);
/* Hidden options */
obs_data_set_default_bool(settings, "repeat_headers", false);
obs_data_set_default_bool(settings, "force_cuda_tex", false);
obs_data_set_default_bool(settings, "disable_scenecut", false);
}
void h264_nvenc_defaults(obs_data_t *settings)
{
nvenc_defaults_base(CODEC_H264, settings);
}
#ifdef ENABLE_HEVC
void hevc_nvenc_defaults(obs_data_t *settings)
{
nvenc_defaults_base(CODEC_HEVC, settings);
}
#endif
void av1_nvenc_defaults(obs_data_t *settings)
{
nvenc_defaults_base(CODEC_AV1, settings);
}
static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p, obs_data_t *settings)
{
const char *rc = obs_data_get_string(settings, "rate_control");
bool cqp = strcmp(rc, "CQP") == 0;
bool vbr = strcmp(rc, "VBR") == 0;
bool cqvbr = strcmp(rc, "CQVBR") == 0;
bool lossless = strcmp(rc, "lossless") == 0;
p = obs_properties_get(ppts, "bitrate");
obs_property_set_visible(p, !cqp && !lossless && !cqvbr);
p = obs_properties_get(ppts, "max_bitrate");
obs_property_set_visible(p, vbr || cqvbr);
p = obs_properties_get(ppts, "target_quality");
obs_property_set_visible(p, cqvbr);
p = obs_properties_get(ppts, "cqp");
obs_property_set_visible(p, cqp);
p = obs_properties_get(ppts, "preset");
obs_property_set_visible(p, !lossless);
p = obs_properties_get(ppts, "tune");
obs_property_set_visible(p, !lossless);
p = obs_properties_get(ppts, "adaptive_quantization");
obs_property_set_visible(p, !lossless);
return true;
}
obs_properties_t *nvenc_properties_internal(enum codec_type codec)
{
obs_properties_t *props = obs_properties_create();
obs_property_t *p;
struct encoder_caps *caps = get_encoder_caps(codec);
p = obs_properties_add_list(props, "rate_control", obs_module_text("RateControl"), OBS_COMBO_TYPE_LIST,
OBS_COMBO_FORMAT_STRING);
obs_property_list_add_string(p, obs_module_text("CBR"), "CBR");
obs_property_list_add_string(p, obs_module_text("CQP"), "CQP");
obs_property_list_add_string(p, obs_module_text("VBR"), "VBR");
obs_property_list_add_string(p, obs_module_text("CQVBR"), "CQVBR");
if (caps->lossless) {
obs_property_list_add_string(p, obs_module_text("Lossless"), "lossless");
}
obs_property_set_modified_callback(p, rate_control_modified);
p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), 50, UINT32_MAX / 1000, 50);
obs_property_int_set_suffix(p, " Kbps");
obs_properties_add_int(props, "target_quality", obs_module_text("TargetQuality"), 1, 51, 1);
p = obs_properties_add_int(props, "max_bitrate", obs_module_text("MaxBitrate"), 0, UINT32_MAX / 1000, 50);
obs_property_int_set_suffix(p, " Kbps");
/* AV1 uses 0-255 instead of 0-51 for QP, and most implementations just
* multiply the value by 4 to keep the range smaller. */
obs_properties_add_int(props, "cqp", obs_module_text("CQP"), 1, codec == CODEC_AV1 ? 63 : 51, 1);
p = obs_properties_add_int(props, "keyint_sec", obs_module_text("KeyframeIntervalSec"), 0, 10, 1);
obs_property_int_set_suffix(p, " s");
p = obs_properties_add_list(props, "preset", obs_module_text("Preset"), OBS_COMBO_TYPE_LIST,
OBS_COMBO_FORMAT_STRING);
#define add_preset(val) obs_property_list_add_string(p, obs_module_text("Preset." val), val)
add_preset("p1");
add_preset("p2");
add_preset("p3");
add_preset("p4");
add_preset("p5");
add_preset("p6");
add_preset("p7");
#undef add_preset
p = obs_properties_add_list(props, "tune", obs_module_text("Tuning"), OBS_COMBO_TYPE_LIST,
OBS_COMBO_FORMAT_STRING);
#define add_tune(val) obs_property_list_add_string(p, obs_module_text("Tuning." val), val)
#ifdef NVENC_12_2_OR_LATER
/* The UHQ tune is only supported on Turing or later.
* It uses the temporal filtering feature, so we can use its
* availability as an indicator that we are on a supported GPU. */
if (codec == CODEC_HEVC && caps->temporal_filter)
add_tune("uhq");
#endif
add_tune("hq");
add_tune("ll");
add_tune("ull");
#undef add_tune
p = obs_properties_add_list(props, "multipass", obs_module_text("Multipass"), OBS_COMBO_TYPE_LIST,
OBS_COMBO_FORMAT_STRING);
#define add_multipass(val) obs_property_list_add_string(p, obs_module_text("Multipass." val), val)
add_multipass("disabled");
add_multipass("qres");
add_multipass("fullres");
#undef add_multipass
p = obs_properties_add_list(props, "profile", obs_module_text("Profile"), OBS_COMBO_TYPE_LIST,
OBS_COMBO_FORMAT_STRING);
#define add_profile(val) obs_property_list_add_string(p, val, val)
if (codec == CODEC_HEVC) {
if (caps->ten_bit)
add_profile("main10");
add_profile("main");
} else if (codec == CODEC_AV1) {
add_profile("main");
} else {
add_profile("high");
add_profile("main");
add_profile("baseline");
}
#undef add_profile
p = obs_properties_add_bool(props, "lookahead", obs_module_text("LookAhead"));
obs_property_set_long_description(p, obs_module_text("LookAhead.ToolTip"));
p = obs_properties_add_bool(props, "adaptive_quantization", obs_module_text("AdaptiveQuantization"));
obs_property_set_long_description(p, obs_module_text("AdaptiveQuantization.ToolTip"));
if (num_encoder_devices() > 1) {
obs_properties_add_int(props, "device", obs_module_text("GPU"), -1, num_encoder_devices(), 1);
}
if (caps->bframes > 0) {
obs_properties_add_int(props, "bf", obs_module_text("BFrames"), 0, caps->bframes, 1);
}
/* H.264 supports this, but seems to cause issues with some decoders,
* so restrict it to the custom options field for now. */
if (caps->bref_modes && codec != CODEC_H264) {
p = obs_properties_add_list(props, "bframe_ref_mode", obs_module_text("BFrameRefMode"),
OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
obs_property_list_add_int(p, obs_module_text("BframeRefMode.Disabled"),
NV_ENC_BFRAME_REF_MODE_DISABLED);
if (caps->bref_modes & 1) {
obs_property_list_add_int(p, obs_module_text("BframeRefMode.Each"),
NV_ENC_BFRAME_REF_MODE_EACH);
}
if (caps->bref_modes & 2) {
obs_property_list_add_int(p, obs_module_text("BframeRefMode.Middle"),
NV_ENC_BFRAME_REF_MODE_MIDDLE);
}
}
#ifdef NVENC_12_1_OR_LATER
/* Some older GPUs such as the 1080 Ti have 2 NVENC chips, but do not
* support split encoding. Therefore, we check for AV1 support here to
* make sure this option is only presented on 40-series and later. */
if (is_codec_supported(CODEC_AV1) && caps->engines > 1 && !has_broken_split_encoding() &&
(codec == CODEC_HEVC || codec == CODEC_AV1)) {
p = obs_properties_add_list(props, "split_encode", obs_module_text("SplitEncode"), OBS_COMBO_TYPE_LIST,
OBS_COMBO_FORMAT_INT);
obs_property_list_add_int(p, obs_module_text("SplitEncode.Auto"), NV_ENC_SPLIT_AUTO_MODE);
obs_property_list_add_int(p, obs_module_text("SplitEncode.Disabled"), NV_ENC_SPLIT_DISABLE_MODE);
obs_property_list_add_int(p, obs_module_text("SplitEncode.Enabled"), NV_ENC_SPLIT_TWO_FORCED_MODE);
if (caps->engines > 2) {
obs_property_list_add_int(p, obs_module_text("SplitEncode.ThreeWay"),
NV_ENC_SPLIT_THREE_FORCED_MODE);
}
}
#endif
p = obs_properties_add_text(props, "opts", obs_module_text("Opts"), OBS_TEXT_DEFAULT);
obs_property_set_long_description(p, obs_module_text("Opts.TT"));
/* Invisible properties */
p = obs_properties_add_bool(props, "repeat_headers", "repeat_headers");
obs_property_set_visible(p, false);
p = obs_properties_add_bool(props, "force_cuda_tex", "force_cuda_tex");
obs_property_set_visible(p, false);
p = obs_properties_add_bool(props, "disable_scenecut", "disable_scenecut");
obs_property_set_visible(p, false);
return props;
}
obs_properties_t *h264_nvenc_properties(void *unused)
{
UNUSED_PARAMETER(unused);
return nvenc_properties_internal(CODEC_H264);
}
#ifdef ENABLE_HEVC
obs_properties_t *hevc_nvenc_properties(void *unused)
{
UNUSED_PARAMETER(unused);
return nvenc_properties_internal(CODEC_HEVC);
}
#endif
obs_properties_t *av1_nvenc_properties(void *unused)
{
UNUSED_PARAMETER(unused);
return nvenc_properties_internal(CODEC_AV1);
}
| 10,645 |
C
|
.c
| 232 | 43.357759 | 107 | 0.715554 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,689 |
obs-scripting-python-import.c
|
obsproject_obs-studio/shared/obs-scripting/obs-scripting-python-import.c
|
/******************************************************************************
Copyright (C) 2023 by Lain Bailey <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include <util/dstr.h>
#include <util/platform.h>
#define NO_REDEFS
#include "obs-scripting-python-import.h"
#ifdef _MSC_VER
#pragma warning(disable : 4152)
#endif
#ifdef _WIN32
#include <windows.h>
#include <io.h>
#define F_OK 0
#define access _access
#define VERSION_PATTERN "%d%d"
#define FILE_PATTERN "python%s.dll"
#define PATH_MAX MAX_PATH
#elif __APPLE__
#define VERSION_PATTERN "%d.%d"
#define FILE_PATTERN "Python.framework/Versions/Current/lib/libpython%s.dylib"
#endif
#define PY_MAJOR_VERSION_MAX 3
#define PY_MINOR_VERSION_MAX 12
bool import_python(const char *python_path, python_version_t *python_version)
{
struct dstr lib_path;
bool success = false;
void *lib = NULL;
if (!python_path)
python_path = "";
if (!python_version) {
blog(LOG_DEBUG, "[Python] Invalid python_version pointer provided.");
goto fail;
}
dstr_init_copy(&lib_path, python_path);
dstr_replace(&lib_path, "\\", "/");
if (!dstr_is_empty(&lib_path)) {
dstr_cat(&lib_path, "/");
}
struct dstr lib_candidate_path;
dstr_init(&lib_candidate_path);
char cur_version[5];
char next_version[5];
snprintf(cur_version, sizeof(cur_version), VERSION_PATTERN, PY_MAJOR_VERSION_MAX, PY_MINOR_VERSION_MAX);
struct dstr temp;
dstr_init(&temp);
dstr_printf(&temp, FILE_PATTERN, cur_version);
int minor_version = PY_MINOR_VERSION_MAX;
do {
dstr_printf(&lib_candidate_path, "%s%s", lib_path.array, temp.array);
if (access(lib_candidate_path.array, F_OK) == 0) {
lib = os_dlopen(lib_candidate_path.array);
}
if (lib) {
break;
}
snprintf(cur_version, sizeof(cur_version), VERSION_PATTERN, PY_MAJOR_VERSION_MAX, minor_version);
snprintf(next_version, sizeof(next_version), VERSION_PATTERN, PY_MAJOR_VERSION_MAX, --minor_version);
dstr_replace(&temp, cur_version, next_version);
} while (minor_version > 5);
dstr_free(&temp);
dstr_free(&lib_candidate_path);
if (!lib) {
blog(LOG_WARNING, "[Python] Could not load library: %s", lib_path.array);
goto fail;
}
python_version->major = PY_MAJOR_VERSION_MAX;
python_version->minor = minor_version;
#define IMPORT_FUNC(x) \
do { \
Import_##x = os_dlsym(lib, #x); \
if (!Import_##x) { \
blog(LOG_WARNING, "[Python] Failed to import: %s", #x); \
goto fail; \
} \
} while (false)
IMPORT_FUNC(PyType_Ready);
IMPORT_FUNC(PyType_Modified);
IMPORT_FUNC(PyType_IsSubtype);
IMPORT_FUNC(PyObject_GenericGetAttr);
IMPORT_FUNC(PyObject_IsTrue);
IMPORT_FUNC(Py_DecRef);
IMPORT_FUNC(PyObject_Malloc);
IMPORT_FUNC(PyObject_Free);
IMPORT_FUNC(PyObject_Init);
IMPORT_FUNC(PyUnicode_FromFormat);
IMPORT_FUNC(PyUnicode_Concat);
IMPORT_FUNC(PyLong_FromVoidPtr);
IMPORT_FUNC(PyLong_FromLong);
IMPORT_FUNC(PyBool_FromLong);
IMPORT_FUNC(PyGILState_Ensure);
IMPORT_FUNC(PyGILState_GetThisThreadState);
IMPORT_FUNC(PyErr_SetString);
IMPORT_FUNC(PyErr_Occurred);
IMPORT_FUNC(PyErr_Fetch);
IMPORT_FUNC(PyErr_Restore);
IMPORT_FUNC(PyErr_WriteUnraisable);
IMPORT_FUNC(PyArg_UnpackTuple);
IMPORT_FUNC(Py_BuildValue);
IMPORT_FUNC(PyRun_SimpleStringFlags);
IMPORT_FUNC(PyErr_Print);
IMPORT_FUNC(Py_SetPythonHome);
IMPORT_FUNC(Py_Initialize);
IMPORT_FUNC(Py_Finalize);
IMPORT_FUNC(Py_IsInitialized);
if (python_version->major == 3 && python_version->minor < 7) {
IMPORT_FUNC(PyEval_InitThreads);
IMPORT_FUNC(PyEval_ThreadsInitialized);
}
IMPORT_FUNC(PyEval_ReleaseThread);
IMPORT_FUNC(PySys_SetArgv);
IMPORT_FUNC(PyImport_ImportModule);
IMPORT_FUNC(PyObject_CallFunctionObjArgs);
IMPORT_FUNC(_Py_NotImplementedStruct);
IMPORT_FUNC(PyExc_TypeError);
IMPORT_FUNC(PyExc_RuntimeError);
IMPORT_FUNC(PyObject_GetAttr);
IMPORT_FUNC(PyUnicode_FromString);
IMPORT_FUNC(PyDict_New);
IMPORT_FUNC(PyDict_GetItemString);
IMPORT_FUNC(PyDict_SetItemString);
IMPORT_FUNC(PyCFunction_NewEx);
if (python_version->major == 3 && python_version->minor >= 9)
IMPORT_FUNC(PyCMethod_New);
IMPORT_FUNC(PyModule_GetDict);
IMPORT_FUNC(PyModule_GetNameObject);
IMPORT_FUNC(PyModule_AddObject);
IMPORT_FUNC(PyModule_AddStringConstant);
IMPORT_FUNC(PyImport_Import);
IMPORT_FUNC(PyObject_CallObject);
IMPORT_FUNC(_Py_FalseStruct);
IMPORT_FUNC(_Py_TrueStruct);
IMPORT_FUNC(PyGILState_Release);
IMPORT_FUNC(PyList_Append);
IMPORT_FUNC(PySys_GetObject);
IMPORT_FUNC(PyImport_ReloadModule);
IMPORT_FUNC(PyObject_GetAttrString);
IMPORT_FUNC(PyCapsule_New);
IMPORT_FUNC(PyCapsule_GetPointer);
IMPORT_FUNC(PyArg_ParseTuple);
IMPORT_FUNC(PyFunction_Type);
IMPORT_FUNC(PyObject_SetAttr);
IMPORT_FUNC(_PyObject_New);
IMPORT_FUNC(PyCapsule_Import);
IMPORT_FUNC(PyErr_Clear);
IMPORT_FUNC(PyObject_Call);
IMPORT_FUNC(PyList_New);
IMPORT_FUNC(PyList_Size);
IMPORT_FUNC(PyList_GetItem);
IMPORT_FUNC(PyUnicode_AsUTF8String);
IMPORT_FUNC(PyLong_FromUnsignedLongLong);
IMPORT_FUNC(PyArg_VaParse);
IMPORT_FUNC(_Py_NoneStruct);
IMPORT_FUNC(PyTuple_New);
if (python_version->major == 3 && python_version->minor >= 9) {
IMPORT_FUNC(PyType_GetFlags);
}
#if defined(Py_DEBUG) || PY_VERSION_HEX >= 0x030900b0
IMPORT_FUNC(_Py_Dealloc);
#endif
#undef IMPORT_FUNC
success = true;
fail:
if (!success && lib)
os_dlclose(lib);
dstr_free(&lib_path);
return success;
}
| 6,353 |
C
|
.c
| 179 | 33.139665 | 105 | 0.696077 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,699 |
cache.h
|
obsproject_obs-studio/shared/media-playback/media-playback/cache.h
|
/*
* Copyright (c) 2023 Lain Bailey <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
#include <util/threading.h>
#include <util/darray.h>
#include <obs.h>
#include "media.h"
struct mp_cache {
mp_video_cb v_preload_cb;
mp_video_cb v_seek_cb;
mp_stop_cb stop_cb;
mp_video_cb v_cb;
mp_audio_cb a_cb;
void *opaque;
bool request_preload;
bool has_video;
bool has_audio;
char *path;
char *format_name;
char *ffmpeg_options;
int buffering;
int speed;
pthread_mutex_t mutex;
os_sem_t *sem;
bool preload_frame;
bool stopping;
bool looping;
bool active;
bool reset;
bool kill;
bool thread_valid;
pthread_t thread;
DARRAY(struct obs_source_frame) video_frames;
DARRAY(struct obs_source_audio) audio_segments;
size_t cur_v_idx;
size_t cur_a_idx;
size_t next_v_idx;
size_t next_a_idx;
int64_t next_v_ts;
int64_t next_a_ts;
int64_t final_v_duration;
int64_t final_a_duration;
int64_t play_sys_ts;
int64_t next_pts_ns;
uint64_t next_ns;
int64_t start_ts;
int64_t base_ts;
bool pause;
bool reset_ts;
bool seek;
bool seek_next_ts;
bool eof;
int64_t seek_pos;
int64_t start_time;
int64_t media_duration;
mp_media_t m;
};
typedef struct mp_cache mp_cache_t;
extern bool mp_cache_init(mp_cache_t *c, const struct mp_media_info *info);
extern void mp_cache_free(mp_cache_t *c);
extern void mp_cache_play(mp_cache_t *c, bool loop);
extern void mp_cache_play_pause(mp_cache_t *c, bool pause);
extern void mp_cache_stop(mp_cache_t *c);
extern void mp_cache_preload_frame(mp_cache_t *c);
extern int64_t mp_cache_get_current_time(mp_cache_t *c);
extern void mp_cache_seek(mp_cache_t *c, int64_t pos);
extern int64_t mp_cache_get_frames(mp_cache_t *c);
extern int64_t mp_cache_get_duration(mp_cache_t *c);
| 2,463 |
C
|
.c
| 81 | 28.444444 | 75 | 0.754438 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,702 |
cache.c
|
obsproject_obs-studio/shared/media-playback/media-playback/cache.c
|
/*
* Copyright (c) 2023 Lain Bailey <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <media-io/audio-io.h>
#include <util/platform.h>
#include "media-playback.h"
#include "cache.h"
#include "media.h"
extern bool mp_media_init2(mp_media_t *m);
extern bool mp_media_prepare_frames(mp_media_t *m);
extern bool mp_media_eof(mp_media_t *m);
extern void mp_media_next_video(mp_media_t *m, bool preload);
extern void mp_media_next_audio(mp_media_t *m);
extern bool mp_media_reset(mp_media_t *m);
static bool mp_cache_reset(mp_cache_t *c);
static int64_t base_sys_ts = 0;
#define v_eof(c) (c->cur_v_idx == c->video_frames.num)
#define a_eof(c) (c->cur_a_idx == c->audio_segments.num)
static inline int64_t mp_cache_get_next_min_pts(mp_cache_t *c)
{
int64_t min_next_ns = 0x7FFFFFFFFFFFFFFFLL;
if (c->has_video && !v_eof(c)) {
min_next_ns = c->next_v_ts;
}
if (c->has_audio && !a_eof(c) && c->next_a_ts < min_next_ns) {
min_next_ns = c->next_a_ts;
}
return min_next_ns;
}
static inline int64_t mp_cache_get_base_pts(mp_cache_t *c)
{
int64_t base_ts = 0;
if (c->has_video && c->next_v_ts > base_ts)
base_ts = c->next_v_ts;
if (c->has_audio && c->next_a_ts > base_ts)
base_ts = c->next_a_ts;
return base_ts;
}
static void reset_ts(mp_cache_t *c)
{
c->base_ts += mp_cache_get_base_pts(c);
c->play_sys_ts = (int64_t)os_gettime_ns();
c->start_ts = c->next_pts_ns = mp_cache_get_next_min_pts(c);
c->next_ns = 0;
}
static inline bool mp_cache_sleep(mp_cache_t *c)
{
bool timeout = false;
if (!c->next_ns) {
c->next_ns = os_gettime_ns();
} else {
const uint64_t t = os_gettime_ns();
if (c->next_ns > t) {
const uint32_t delta_ms = (uint32_t)((c->next_ns - t + 500000) / 1000000);
if (delta_ms > 0) {
static const uint32_t timeout_ms = 200;
timeout = delta_ms > timeout_ms;
os_sleep_ms(timeout ? timeout_ms : delta_ms);
}
}
}
return timeout;
}
static bool mp_cache_eof(mp_cache_t *c)
{
bool v_ended = !c->has_video || v_eof(c);
bool a_ended = !c->has_audio || a_eof(c);
bool eof = v_ended && a_ended;
if (!eof)
return false;
pthread_mutex_lock(&c->mutex);
if (!c->looping) {
c->active = false;
c->stopping = true;
}
pthread_mutex_unlock(&c->mutex);
mp_cache_reset(c);
return true;
}
bool mp_cache_decode(mp_cache_t *c)
{
mp_media_t *m = &c->m;
bool success = false;
m->full_decode = true;
mp_media_reset(m);
while (!mp_media_eof(m)) {
if (m->has_video)
mp_media_next_video(m, false);
if (m->has_audio)
mp_media_next_audio(m);
if (!mp_media_prepare_frames(m))
goto fail;
}
success = true;
c->start_time = c->m.fmt->start_time;
if (c->start_time == AV_NOPTS_VALUE)
c->start_time = 0;
fail:
mp_media_free(m);
return success;
}
static void seek_to(mp_cache_t *c, int64_t pos)
{
size_t new_v_idx = 0;
size_t new_a_idx = 0;
if (pos > c->media_duration) {
blog(LOG_WARNING, "MP: Invalid seek position");
return;
}
if (c->has_video) {
struct obs_source_frame *v;
for (size_t i = 0; i < c->video_frames.num; i++) {
v = &c->video_frames.array[i];
new_v_idx = i;
if ((int64_t)v->timestamp >= pos) {
break;
}
}
size_t next_idx = new_v_idx + 1;
if (next_idx == c->video_frames.num) {
c->next_v_ts = (int64_t)v->timestamp + c->final_v_duration;
} else {
struct obs_source_frame *next = &c->video_frames.array[next_idx];
c->next_v_ts = (int64_t)next->timestamp;
}
}
if (c->has_audio) {
struct obs_source_audio *a;
for (size_t i = 0; i < c->audio_segments.num; i++) {
a = &c->audio_segments.array[i];
new_a_idx = i;
if ((int64_t)a->timestamp >= pos) {
break;
}
}
size_t next_idx = new_a_idx + 1;
if (next_idx == c->audio_segments.num) {
c->next_a_ts = (int64_t)a->timestamp + c->final_a_duration;
} else {
struct obs_source_audio *next = &c->audio_segments.array[next_idx];
c->next_a_ts = (int64_t)next->timestamp;
}
}
c->cur_v_idx = c->next_v_idx = new_v_idx;
c->cur_a_idx = c->next_a_idx = new_a_idx;
}
/* maximum timestamp variance in nanoseconds */
#define MAX_TS_VAR 2000000000LL
static inline bool mp_media_can_play_video(mp_cache_t *c)
{
return !v_eof(c) && (c->next_v_ts <= c->next_pts_ns || (c->next_v_ts - c->next_pts_ns > MAX_TS_VAR));
}
static inline bool mp_media_can_play_audio(mp_cache_t *c)
{
return !a_eof(c) && (c->next_a_ts <= c->next_pts_ns || (c->next_a_ts - c->next_pts_ns > MAX_TS_VAR));
}
static inline void calc_next_v_ts(mp_cache_t *c, struct obs_source_frame *frame)
{
int64_t offset;
if (c->next_v_idx < c->video_frames.num) {
struct obs_source_frame *next = &c->video_frames.array[c->next_v_idx];
offset = (int64_t)(next->timestamp - frame->timestamp);
} else {
offset = c->final_v_duration;
}
c->next_v_ts += offset;
}
static inline void calc_next_a_ts(mp_cache_t *c, struct obs_source_audio *audio)
{
int64_t offset;
if (c->next_a_idx < c->audio_segments.num) {
struct obs_source_audio *next = &c->audio_segments.array[c->next_a_idx];
offset = (int64_t)(next->timestamp - audio->timestamp);
} else {
offset = c->final_a_duration;
}
c->next_a_ts += offset;
}
static void mp_cache_next_video(mp_cache_t *c, bool preload)
{
/* eof check */
if (c->next_v_idx == c->video_frames.num) {
if (mp_media_can_play_video(c))
c->cur_v_idx = c->next_v_idx;
return;
}
struct obs_source_frame *frame = &c->video_frames.array[c->next_v_idx];
struct obs_source_frame dup = *frame;
dup.timestamp = c->base_ts + dup.timestamp - c->start_ts + c->play_sys_ts - base_sys_ts;
if (!preload) {
if (!mp_media_can_play_video(c))
return;
if (c->v_cb)
c->v_cb(c->opaque, &dup);
if (c->cur_v_idx < c->next_v_idx)
++c->cur_v_idx;
++c->next_v_idx;
calc_next_v_ts(c, frame);
} else {
if (c->seek_next_ts && c->v_seek_cb) {
c->v_seek_cb(c->opaque, &dup);
} else if (!c->request_preload) {
c->v_preload_cb(c->opaque, &dup);
}
}
}
static void mp_cache_next_audio(mp_cache_t *c)
{
/* eof check */
if (c->next_a_idx == c->audio_segments.num) {
if (mp_media_can_play_audio(c))
c->cur_a_idx = c->next_a_idx;
return;
}
if (!mp_media_can_play_audio(c))
return;
struct obs_source_audio *audio = &c->audio_segments.array[c->next_a_idx];
struct obs_source_audio dup = *audio;
dup.timestamp = c->base_ts + dup.timestamp - c->start_ts + c->play_sys_ts - base_sys_ts;
if (c->a_cb)
c->a_cb(c->opaque, &dup);
if (c->cur_a_idx < c->next_a_idx)
++c->cur_a_idx;
++c->next_a_idx;
calc_next_a_ts(c, audio);
}
static bool mp_cache_reset(mp_cache_t *c)
{
bool stopping;
bool active;
int64_t next_ts = mp_cache_get_base_pts(c);
int64_t offset = next_ts - c->next_pts_ns;
int64_t start_time = c->start_time;
c->eof = false;
c->base_ts += next_ts;
c->seek_next_ts = false;
seek_to(c, start_time);
pthread_mutex_lock(&c->mutex);
stopping = c->stopping;
active = c->active;
c->stopping = false;
pthread_mutex_unlock(&c->mutex);
if (c->has_video) {
size_t next_idx = c->video_frames.num > 1 ? 1 : 0;
c->cur_v_idx = c->next_v_idx = 0;
c->next_v_ts = c->video_frames.array[next_idx].timestamp;
}
if (c->has_audio) {
size_t next_idx = c->audio_segments.num > 1 ? 1 : 0;
c->cur_a_idx = c->next_a_idx = 0;
c->next_a_ts = c->audio_segments.array[next_idx].timestamp;
}
if (active) {
if (!c->play_sys_ts)
c->play_sys_ts = (int64_t)os_gettime_ns();
c->start_ts = c->next_pts_ns = mp_cache_get_next_min_pts(c);
if (c->next_ns)
c->next_ns += offset;
} else {
c->start_ts = c->next_pts_ns = mp_cache_get_next_min_pts(c);
c->play_sys_ts = (int64_t)os_gettime_ns();
c->next_ns = 0;
}
c->pause = false;
if (!active && c->v_preload_cb)
mp_cache_next_video(c, true);
if (stopping && c->stop_cb)
c->stop_cb(c->opaque);
return true;
}
static void mp_cache_calc_next_ns(mp_cache_t *c)
{
int64_t min_next_ns = mp_cache_get_next_min_pts(c);
int64_t delta = min_next_ns - c->next_pts_ns;
if (c->seek_next_ts) {
delta = 0;
c->seek_next_ts = false;
} else {
#ifdef _DEBUG
assert(delta >= 0);
#endif
if (delta < 0)
delta = 0;
if (delta > 3000000000)
delta = 0;
}
c->next_ns += delta;
c->next_pts_ns = min_next_ns;
}
static inline bool mp_cache_thread(mp_cache_t *c)
{
os_set_thread_name("mp_cache_thread");
if (!mp_cache_decode(c)) {
return false;
}
for (;;) {
bool reset, kill, is_active, seek, pause, reset_time, preload_frame;
int64_t seek_pos;
bool timeout = false;
pthread_mutex_lock(&c->mutex);
is_active = c->active;
pause = c->pause;
pthread_mutex_unlock(&c->mutex);
if (!is_active || pause) {
if (os_sem_wait(c->sem) < 0)
return false;
if (pause)
reset_ts(c);
} else {
timeout = mp_cache_sleep(c);
}
pthread_mutex_lock(&c->mutex);
reset = c->reset;
kill = c->kill;
c->reset = false;
c->kill = false;
preload_frame = c->preload_frame;
pause = c->pause;
seek_pos = c->seek_pos;
seek = c->seek;
reset_time = c->reset_ts;
c->preload_frame = false;
c->seek = false;
c->reset_ts = false;
pthread_mutex_unlock(&c->mutex);
if (kill) {
break;
}
if (reset) {
mp_cache_reset(c);
continue;
}
if (seek) {
c->seek_next_ts = true;
seek_to(c, seek_pos);
continue;
}
if (reset_time) {
reset_ts(c);
continue;
}
if (pause)
continue;
if (preload_frame)
c->v_preload_cb(c->opaque, &c->video_frames.array[0]);
/* frames are ready */
if (is_active && !timeout) {
if (c->has_video)
mp_cache_next_video(c, false);
if (c->has_audio)
mp_cache_next_audio(c);
if (mp_cache_eof(c))
continue;
mp_cache_calc_next_ns(c);
}
}
return true;
}
static void *mp_cache_thread_start(void *opaque)
{
mp_cache_t *c = opaque;
if (!mp_cache_thread(c)) {
if (c->stop_cb) {
c->stop_cb(c->opaque);
}
}
return NULL;
}
static void fill_video(void *data, struct obs_source_frame *frame)
{
mp_cache_t *c = data;
struct obs_source_frame dup;
obs_source_frame_init(&dup, frame->format, frame->width, frame->height);
obs_source_frame_copy(&dup, frame);
dup.timestamp = frame->timestamp;
c->final_v_duration = c->m.v.last_duration;
da_push_back(c->video_frames, &dup);
}
static void fill_audio(void *data, struct obs_source_audio *audio)
{
mp_cache_t *c = data;
struct obs_source_audio dup = *audio;
size_t size = get_total_audio_size(dup.format, dup.speakers, dup.frames);
dup.data[0] = bmalloc(size);
size_t planes = get_audio_planes(dup.format, dup.speakers);
if (planes > 1) {
size = get_audio_bytes_per_channel(dup.format) * dup.frames;
uint8_t *out = (uint8_t *)dup.data[0];
for (size_t i = 0; i < planes; i++) {
if (i > 0)
dup.data[i] = out;
memcpy(out, audio->data[i], size);
out += size;
}
} else {
memcpy((uint8_t *)dup.data[0], audio->data[0], size);
}
c->final_a_duration = c->m.a.last_duration;
da_push_back(c->audio_segments, &dup);
}
static inline bool mp_cache_init_internal(mp_cache_t *c, const struct mp_media_info *info)
{
if (pthread_mutex_init(&c->mutex, NULL) != 0) {
blog(LOG_WARNING, "MP: Failed to init mutex");
return false;
}
if (os_sem_init(&c->sem, 0) != 0) {
blog(LOG_WARNING, "MP: Failed to init semaphore");
return false;
}
c->path = info->path ? bstrdup(info->path) : NULL;
c->format_name = info->format ? bstrdup(info->format) : NULL;
if (pthread_create(&c->thread, NULL, mp_cache_thread_start, c) != 0) {
blog(LOG_WARNING, "MP: Could not create media thread");
return false;
}
c->thread_valid = true;
return true;
}
bool mp_cache_init(mp_cache_t *c, const struct mp_media_info *info)
{
struct mp_media_info info2 = *info;
info2.opaque = c;
info2.v_cb = fill_video;
info2.a_cb = fill_audio;
info2.v_preload_cb = NULL;
info2.v_seek_cb = NULL;
info2.stop_cb = NULL;
info2.full_decode = true;
mp_media_t *m = &c->m;
pthread_mutex_init_value(&c->mutex);
if (!mp_media_init(m, &info2)) {
mp_cache_free(c);
return false;
}
if (!mp_media_init2(m)) {
mp_cache_free(c);
return false;
}
c->opaque = info->opaque;
c->v_cb = info->v_cb;
c->a_cb = info->a_cb;
c->stop_cb = info->stop_cb;
c->ffmpeg_options = info->ffmpeg_options;
c->v_seek_cb = info->v_seek_cb;
c->v_preload_cb = info->v_preload_cb;
c->request_preload = info->request_preload;
c->speed = info->speed;
c->media_duration = m->fmt->duration;
c->has_video = m->has_video;
c->has_audio = m->has_audio;
if (!base_sys_ts)
base_sys_ts = (int64_t)os_gettime_ns();
if (!mp_cache_init_internal(c, info)) {
mp_cache_free(c);
return false;
}
return true;
}
static void mp_kill_thread(mp_cache_t *c)
{
if (c->thread_valid) {
pthread_mutex_lock(&c->mutex);
c->kill = true;
pthread_mutex_unlock(&c->mutex);
os_sem_post(c->sem);
pthread_join(c->thread, NULL);
}
}
void mp_cache_free(mp_cache_t *c)
{
if (!c)
return;
mp_cache_stop(c);
mp_kill_thread(c);
if (c->m.fmt)
mp_media_free(&c->m);
for (size_t i = 0; i < c->video_frames.num; i++) {
struct obs_source_frame *f = &c->video_frames.array[i];
obs_source_frame_free(f);
}
for (size_t i = 0; i < c->audio_segments.num; i++) {
struct obs_source_audio *a = &c->audio_segments.array[i];
bfree((void *)a->data[0]);
}
da_free(c->video_frames);
da_free(c->audio_segments);
bfree(c->path);
bfree(c->format_name);
pthread_mutex_destroy(&c->mutex);
os_sem_destroy(c->sem);
memset(c, 0, sizeof(*c));
}
void mp_cache_play(mp_cache_t *c, bool loop)
{
pthread_mutex_lock(&c->mutex);
if (c->active)
c->reset = true;
c->looping = loop;
c->active = true;
pthread_mutex_unlock(&c->mutex);
os_sem_post(c->sem);
}
void mp_cache_play_pause(mp_cache_t *c, bool pause)
{
pthread_mutex_lock(&c->mutex);
if (c->active) {
c->pause = pause;
c->reset_ts = !pause;
}
pthread_mutex_unlock(&c->mutex);
os_sem_post(c->sem);
}
void mp_cache_stop(mp_cache_t *c)
{
pthread_mutex_lock(&c->mutex);
if (c->active) {
c->reset = true;
c->active = false;
c->stopping = true;
}
pthread_mutex_unlock(&c->mutex);
os_sem_post(c->sem);
}
void mp_cache_preload_frame(mp_cache_t *c)
{
if (c->request_preload && c->thread_valid && c->v_preload_cb) {
pthread_mutex_lock(&c->mutex);
c->preload_frame = true;
pthread_mutex_unlock(&c->mutex);
os_sem_post(c->sem);
}
}
int64_t mp_cache_get_current_time(mp_cache_t *c)
{
return mp_cache_get_base_pts(c) * (int64_t)c->speed / 100000000LL;
}
void mp_cache_seek(mp_cache_t *c, int64_t pos)
{
pthread_mutex_lock(&c->mutex);
if (c->active) {
c->seek = true;
c->seek_pos = pos * 1000;
}
pthread_mutex_unlock(&c->mutex);
os_sem_post(c->sem);
}
int64_t mp_cache_get_frames(mp_cache_t *c)
{
return c->video_frames.num;
}
int64_t mp_cache_get_duration(mp_cache_t *c)
{
return c->media_duration;
}
| 15,444 |
C
|
.c
| 567 | 24.693122 | 102 | 0.648782 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,703 |
media-playback.h
|
obsproject_obs-studio/shared/media-playback/media-playback/media-playback.h
|
/*
* Copyright (c) 2023 Lain Bailey <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
#include <obs.h>
struct media_playback;
typedef struct media_playback media_playback_t;
typedef void (*mp_video_cb)(void *opaque, struct obs_source_frame *frame);
typedef void (*mp_audio_cb)(void *opaque, struct obs_source_audio *audio);
typedef void (*mp_stop_cb)(void *opaque);
struct mp_media_info {
void *opaque;
mp_video_cb v_cb;
mp_video_cb v_preload_cb;
mp_video_cb v_seek_cb;
mp_audio_cb a_cb;
mp_stop_cb stop_cb;
const char *path;
const char *format;
char *ffmpeg_options;
int buffering;
int speed;
enum video_range_type force_range;
bool is_linear_alpha;
bool hardware_decoding;
bool is_local_file;
bool reconnecting;
bool request_preload;
bool full_decode;
};
extern media_playback_t *media_playback_create(const struct mp_media_info *info);
extern void media_playback_destroy(media_playback_t *mp);
extern void media_playback_play(media_playback_t *mp, bool looping, bool reconnecting);
extern void media_playback_play_pause(media_playback_t *mp, bool pause);
extern void media_playback_stop(media_playback_t *mp);
extern void media_playback_set_looping(media_playback_t *mp, bool looping);
extern void media_playback_set_is_linear_alpha(media_playback_t *mp, bool is_linear_alpha);
extern void media_playback_preload_frame(media_playback_t *mp);
extern int64_t media_playback_get_current_time(media_playback_t *mp);
extern void media_playback_seek(media_playback_t *mp, int64_t pos);
extern int64_t media_playback_get_frames(media_playback_t *mp);
extern int64_t media_playback_get_duration(media_playback_t *mp);
extern bool media_playback_has_video(media_playback_t *mp);
extern bool media_playback_has_audio(media_playback_t *mp);
| 2,479 |
C
|
.c
| 56 | 42.535714 | 91 | 0.781276 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,705 |
media-playback.c
|
obsproject_obs-studio/shared/media-playback/media-playback/media-playback.c
|
/*
* Copyright (c) 2023 Lain Bailey <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "media-playback.h"
#include "media.h"
#include "cache.h"
struct media_playback {
bool is_cached;
union {
mp_media_t media;
mp_cache_t cache;
};
};
media_playback_t *media_playback_create(const struct mp_media_info *info)
{
media_playback_t *mp = bzalloc(sizeof(*mp));
mp->is_cached = info->is_local_file && info->full_decode;
if ((mp->is_cached && !mp_cache_init(&mp->cache, info)) ||
(!mp->is_cached && !mp_media_init(&mp->media, info))) {
bfree(mp);
return NULL;
}
return mp;
}
void media_playback_destroy(media_playback_t *mp)
{
if (!mp)
return;
if (mp->is_cached)
mp_cache_free(&mp->cache);
else
mp_media_free(&mp->media);
bfree(mp);
}
void media_playback_play(media_playback_t *mp, bool looping, bool reconnecting)
{
if (!mp)
return;
if (mp->is_cached)
mp_cache_play(&mp->cache, looping);
else
mp_media_play(&mp->media, looping, reconnecting);
}
void media_playback_play_pause(media_playback_t *mp, bool pause)
{
if (!mp)
return;
if (mp->is_cached)
mp_cache_play_pause(&mp->cache, pause);
else
mp_media_play_pause(&mp->media, pause);
}
void media_playback_stop(media_playback_t *mp)
{
if (!mp)
return;
if (mp->is_cached)
mp_cache_stop(&mp->cache);
else
mp_media_stop(&mp->media);
}
void media_playback_set_looping(media_playback_t *mp, bool looping)
{
if (mp->is_cached)
mp->cache.looping = looping;
else
mp->media.looping = looping;
}
void media_playback_set_is_linear_alpha(media_playback_t *mp, bool is_linear_alpha)
{
if (mp->is_cached)
mp->cache.m.is_linear_alpha = is_linear_alpha;
else
mp->media.is_linear_alpha = is_linear_alpha;
}
void media_playback_preload_frame(media_playback_t *mp)
{
if (!mp)
return;
if (mp->is_cached)
mp_cache_preload_frame(&mp->cache);
else
mp_media_preload_frame(&mp->media);
}
int64_t media_playback_get_current_time(media_playback_t *mp)
{
if (!mp)
return 0;
if (mp->is_cached)
return mp_cache_get_current_time(&mp->cache);
else
return mp_media_get_current_time(&mp->media);
}
void media_playback_seek(media_playback_t *mp, int64_t pos)
{
if (mp->is_cached)
mp_cache_seek(&mp->cache, pos);
else
mp_media_seek(&mp->media, pos);
}
int64_t media_playback_get_frames(media_playback_t *mp)
{
if (!mp)
return 0;
if (mp->is_cached)
return mp_cache_get_frames(&mp->cache);
else
return mp_media_get_frames(&mp->media);
}
int64_t media_playback_get_duration(media_playback_t *mp)
{
if (!mp)
return 0;
if (mp->is_cached)
return mp_cache_get_duration(&mp->cache);
else
return mp_media_get_duration(&mp->media);
}
bool media_playback_has_video(media_playback_t *mp)
{
if (!mp)
return false;
if (mp->is_cached)
return mp->cache.has_video;
else
return mp->media.has_video;
}
bool media_playback_has_audio(media_playback_t *mp)
{
if (!mp)
return false;
if (mp->is_cached)
return mp->cache.has_audio;
else
return mp->media.has_audio;
}
| 3,720 |
C
|
.c
| 148 | 22.972973 | 83 | 0.720372 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
2,722 |
happy-eyeballs.c
|
obsproject_obs-studio/shared/happy-eyeballs/happy-eyeballs.c
|
/**
* Copyright (c) 2023 Twitch Interactive, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "happy-eyeballs.h"
#include "util/darray.h"
#include "util/dstr.h"
#include "util/platform.h"
#include "util/threading.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#ifdef _MSC_VER
#pragma warning(disable : 4996) /* depricated warnings */
#endif
#include <winsock2.h>
#include <ws2tcpip.h>
#define GetSockError() WSAGetLastError()
#ifdef _MSC_VER
#define snprintf _snprintf
#endif
#else /* !_WIN32 */
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define GetSockError() errno
#endif
/* ------------------------------------------------------------------------- */
/* happy eyeballs coefficients */
/* this is the same default as libcurl */
#define HAPPY_EYEBALLS_DELAY_MS 200
#define HAPPY_EYEBALLS_MAX_ATTEMPTS 6
/* Total time to wait for sockets or to finish trying; whichever is shorter */
#define HAPPY_EYEBALLS_CONNECTION_TIMEOUT_MS 25000
/* ------------------------------------------------------------------------- */
#ifndef INVALID_SOCKET
#define INVALID_SOCKET ~0
#endif
#define STATUS_SUCCESS 0
#define STATUS_FAILURE -1
#define STATUS_INVALID_ARGUMENT -EINVAL
struct happy_eyeballs_candidate {
SOCKET sockfd;
os_event_t *socket_completed_event;
pthread_t thread;
int error;
};
struct happy_eyeballs_ctx {
/**
* socket_fd will be non-zero upon successful connection to the host
* and port specified.
*/
SOCKET socket_fd;
/**
* winner_addr will be non-zero upon successful connection to the host
* and port specified.
*/
struct sockaddr_storage winner_addr;
/**
* winner_addr_len will be non-zero upon successful connection to the
* host and port specified.
*/
socklen_t winner_addr_len;
/**
* error will be non-zero in case of an error during operation.
*/
int error;
/**
* error_message may be set when there is a non-zero error code.
*/
const char *error_message;
/**
* Set along with bind_addr to hint which interface to use.
*/
socklen_t bind_addr_len;
/**
* Set along with bind_addr_len to hint which interface to use.
*/
struct sockaddr_storage bind_addr;
/**
* List of in-flight connection attempts.
*/
DARRAY(struct happy_eyeballs_candidate) candidates;
/**
* Protects against multiple simultaneous winners writing socket_fd,
* winner_addr, and winner_addr_len
*/
pthread_mutex_t winner_mutex;
/**
* Protects against mutating while iterating the candidate list
*/
pthread_mutex_t candidate_mutex;
/**
* Event that signals completion of the race, either via winner or
* error
*/
os_event_t *race_completed_event;
/**
* Addresses gathered by getaddrinfo
*/
struct addrinfo *addresses;
/**
* Domain name resolution time, in nanoseconds (0 until resolution
* success)
*/
uint64_t name_resolution_time_ns;
/**
* Connection time, in nanoseconds
*/
uint64_t connection_time_start;
uint64_t connection_time_end;
/**
* Indicates whether we are in the initial phase of dispatching
* connections, or if we are waiting for things to connect or time out.
*/
volatile bool is_starting;
};
struct happy_connect_worker_args {
SOCKET sockfd;
struct happy_eyeballs_ctx *context;
struct happy_eyeballs_candidate *candidate;
struct addrinfo *address;
};
static int check_comodo(struct happy_eyeballs_ctx *context)
{
#ifdef _WIN32
/* COMODO security software sandbox blocks all DNS by returning "host
* not found" */
HOSTENT *h = gethostbyname("localhost");
if (!h && GetLastError() == WSAHOST_NOT_FOUND) {
context->error = WSAHOST_NOT_FOUND;
context->error_message = "happy-eyeballs: Connection test failed. "
"This error is likely caused by Comodo Internet "
"Security running OBS in sandbox mode. Please add "
"OBS to the Comodo automatic sandbox exclusion list, "
"restart OBS and try again (11001).";
return STATUS_FAILURE;
}
#else
(void)context;
#endif
return STATUS_SUCCESS;
}
static int build_addr_list(const char *hostname, int port, struct happy_eyeballs_ctx *context)
{
struct addrinfo hints = {0};
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_ADDRCONFIG;
if (context->bind_addr_len == sizeof(struct sockaddr_in))
hints.ai_family = AF_INET;
else if (context->bind_addr_len == sizeof(struct sockaddr_in6))
hints.ai_family = AF_INET6;
struct dstr port_str;
dstr_init(&port_str);
dstr_printf(&port_str, "%d", port);
uint64_t start_time = os_gettime_ns();
int err = getaddrinfo(hostname, port_str.array, &hints, &context->addresses);
context->name_resolution_time_ns = os_gettime_ns() - start_time;
dstr_free(&port_str);
if (err) {
context->error = GetSockError();
context->error_message = strerror(GetSockError());
return STATUS_FAILURE;
}
/* Reorder addresses interleaving address family */
struct addrinfo *prev = context->addresses;
struct addrinfo *cur = prev->ai_next;
while (cur) {
if (prev->ai_family == cur->ai_family && (cur->ai_family == AF_INET || cur->ai_family == AF_INET6)) {
/* If the current protocol family matches the previous
* one, look for the next instance of the other kind */
const int target_family = prev->ai_family == AF_INET ? AF_INET6 : AF_INET;
struct addrinfo *it = cur->ai_next;
struct addrinfo *prev_it = cur;
while (it) {
if (it->ai_family == target_family)
break;
prev_it = it;
it = it->ai_next;
}
if (!it) {
/* we're at the end and haven't found the other
* kind, exit the loop early. */
break;
}
prev->ai_next = it;
prev_it->ai_next = it->ai_next;
it->ai_next = cur;
}
prev = cur;
cur = cur->ai_next;
}
return STATUS_SUCCESS;
}
static void signal_end(struct happy_eyeballs_ctx *context)
{
if (os_event_try(context->race_completed_event) != EAGAIN)
return;
context->connection_time_end = os_gettime_ns();
os_event_signal(context->race_completed_event);
}
/**
* Takes the errors that may have been generated by workers, finds the most
* common one, and sets that to be the overall context error.
*/
static int coalesce_errors(struct happy_eyeballs_ctx *context)
{
/* Don't coalesce errors while starting */
if (os_atomic_load_bool(&context->is_starting))
return STATUS_FAILURE;
/* Don't coalesce errors if we've already completed */
if (os_event_try(context->race_completed_event) != EAGAIN)
return STATUS_FAILURE;
/* We'll use the mode of the errors for now. */
struct mode {
int error;
int count;
};
DARRAY(struct mode) modes = {0};
da_init(modes);
/* Gather all the errors into counts for each error */
pthread_mutex_lock(&context->candidate_mutex);
for (size_t i = 0; i < context->candidates.num; i++) {
int err = context->candidates.array[i].error;
struct mode *mode = NULL;
/* If the error is 0, just move on. */
if (err == 0) {
continue;
}
/* Find an existing index containing this error if it exists */
for (size_t j = 0; j < modes.num && mode == NULL; j++) {
if (modes.array[j].error == err)
mode = &modes.array[j];
}
/* Existing index doesn't exist, take the next available. */
if (mode == NULL) {
mode = da_push_back_new(modes);
}
/* Note the error code and increment the count. */
mode->error = err;
mode->count++;
}
pthread_mutex_unlock(&context->candidate_mutex);
int max_count = 0;
int max_value = 0;
/* Find the error with the most occurrences. */
for (size_t i = 0; i < modes.num; i++) {
if (max_count < modes.array[i].count) {
max_value = modes.array[i].error;
max_count = modes.array[i].count;
}
}
da_free(modes);
/* Set the error */
context->error = max_value;
context->error_message = strerror(context->error);
return STATUS_SUCCESS;
}
static void *happy_connect_worker(void *arg)
{
struct happy_connect_worker_args *args = (struct happy_connect_worker_args *)arg;
struct happy_eyeballs_ctx *context = args->context;
if (args->sockfd == INVALID_SOCKET) {
goto success;
}
if (os_event_try(args->context->race_completed_event) == 0) {
/* Already lost, don't bother */
goto success;
}
#if !defined(_WIN32) && defined(SO_NOSIGPIPE)
setsockopt(args->sockfd, SOL_SOCKET, SO_NOSIGPIPE, &(int){1}, sizeof(int));
#endif
if (context->bind_addr.ss_family != 0 &&
bind(args->sockfd, (const struct sockaddr *)&context->bind_addr, context->bind_addr_len) < 0) {
goto failure;
}
if (connect(args->sockfd, args->address->ai_addr, (int)args->address->ai_addrlen) == 0) {
/* success, check if we're the winner. */
pthread_mutex_lock(&context->winner_mutex);
os_event_signal(args->candidate->socket_completed_event);
if (os_event_try(context->race_completed_event) == EAGAIN) {
/* We are the winner. */
context->socket_fd = args->sockfd;
memcpy(&context->winner_addr, args->address->ai_addr, args->address->ai_addrlen);
context->winner_addr_len = (socklen_t)args->address->ai_addrlen;
signal_end(context);
}
pthread_mutex_unlock(&context->winner_mutex);
goto success;
}
failure:
/* failure, note down the error */
args->candidate->error = GetSockError();
pthread_mutex_lock(&context->winner_mutex);
os_event_signal(args->candidate->socket_completed_event);
/* connection candidates may still be getting dispatched, treat as if
* there's an active candidate */
bool active = os_atomic_load_bool(&context->is_starting);
/* check if we are the last worker running. If so, we'll set the error
* status and signal the completion event. */
pthread_mutex_lock(&context->candidate_mutex);
for (size_t i = 0; i < context->candidates.num && !active; i++) {
active = os_event_try(context->candidates.array[i].socket_completed_event) == EAGAIN;
}
pthread_mutex_unlock(&context->candidate_mutex);
pthread_mutex_unlock(&context->winner_mutex);
if (active || context->error != 0) {
/* we're not last or there is already an error on the context,
* let's exit. */
goto success;
}
/* Ok, we are last. Coalesce errors and signal completion. */
if (coalesce_errors(context) == STATUS_SUCCESS)
signal_end(context);
success:
free(args);
return NULL;
}
static int launch_worker(struct happy_eyeballs_ctx *context, struct addrinfo *addr)
{
#ifdef _WIN32
SOCKET fd = WSASocket(addr->ai_family, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
#else
SOCKET fd = socket(addr->ai_family, SOCK_STREAM, IPPROTO_TCP);
#endif
if (fd == INVALID_SOCKET) {
context->error = GetSockError();
return STATUS_FAILURE;
}
pthread_mutex_lock(&context->candidate_mutex);
struct happy_eyeballs_candidate *candidate = da_push_back_new(context->candidates);
candidate->sockfd = fd;
struct happy_connect_worker_args *args =
(struct happy_connect_worker_args *)malloc(sizeof(struct happy_connect_worker_args));
if (args == NULL) {
context->error = ENOMEM;
context->error_message = "happy-eyeballs: Failed to allocate "
"memory for worker context";
pthread_mutex_unlock(&context->candidate_mutex);
return STATUS_FAILURE;
}
int result = os_event_init(&candidate->socket_completed_event, OS_EVENT_TYPE_MANUAL);
if (result != 0) {
/* failure to create the socket completed event */
context->error = result;
context->error_message = "happy-eyeballs: Failed to initialize "
"socket completed event";
free(args);
pthread_mutex_unlock(&context->candidate_mutex);
return STATUS_FAILURE;
}
args->sockfd = fd;
args->address = addr;
args->context = context;
args->candidate = candidate;
pthread_mutex_unlock(&context->candidate_mutex);
/* Launch worker thread; `args` ownership is passed to this thread */
result = pthread_create(&candidate->thread, NULL, happy_connect_worker, args);
if (result != 0) {
/* failure to start the worker thread */
context->error = result;
context->error_message = strerror(result);
os_event_destroy(candidate->socket_completed_event);
free(args);
pthread_mutex_lock(&context->candidate_mutex);
da_erase_item(context->candidates, candidate);
pthread_mutex_unlock(&context->candidate_mutex);
return STATUS_FAILURE;
}
return STATUS_SUCCESS;
}
/* ------------------------------------------------------------------------- */
/* Public functions */
int happy_eyeballs_create(struct happy_eyeballs_ctx **context)
{
if (context == NULL)
return STATUS_INVALID_ARGUMENT;
struct happy_eyeballs_ctx *ctx = (struct happy_eyeballs_ctx *)malloc(sizeof(struct happy_eyeballs_ctx));
if (ctx == NULL)
return -ENOMEM;
memset(ctx, 0, sizeof(struct happy_eyeballs_ctx));
ctx->socket_fd = INVALID_SOCKET;
da_init(ctx->candidates);
da_reserve(ctx->candidates, HAPPY_EYEBALLS_MAX_ATTEMPTS);
/* race_completed_event will be signalled when there is a winner or all
* attempts have failed */
int result = os_event_init(&ctx->race_completed_event, OS_EVENT_TYPE_MANUAL);
/* this mutex is used to avoid the situation where we may have two
* simultaneous winners and inconsistent values set to the context. */
if (result == 0)
result = pthread_mutex_init(&ctx->winner_mutex, NULL);
bool have_winner_mutex = result == 0;
/* this mutex is used to avoid the situation where we may be mutating
* the candidate array while iterating it. */
if (result == 0)
result = pthread_mutex_init(&ctx->candidate_mutex, NULL);
bool have_candidate_mutex = result == 0;
if (result == 0) {
*context = ctx;
return STATUS_SUCCESS;
}
/* Failure, cleanup */
if (ctx->race_completed_event)
os_event_destroy((*context)->race_completed_event);
if (have_winner_mutex)
pthread_mutex_destroy(&(*context)->winner_mutex);
if (have_candidate_mutex)
pthread_mutex_destroy(&(*context)->candidate_mutex);
free(ctx);
*context = NULL;
/* Error codes from pthread_mutex_init are positive, os_event_init is
* negative. We have promised to return negative error codes, so we are
* making them all negative here. */
return -abs(result);
}
int happy_eyeballs_connect(struct happy_eyeballs_ctx *context, const char *hostname, int port)
{
if (hostname == NULL || context == NULL || port == 0)
return STATUS_INVALID_ARGUMENT;
int result = check_comodo(context);
if (result == STATUS_SUCCESS)
result = build_addr_list(hostname, port, context);
if (result != STATUS_SUCCESS)
return result;
context->connection_time_start = os_gettime_ns();
int prev_family = 0;
struct addrinfo *next = context->addresses;
os_atomic_store_bool(&context->is_starting, true);
/* Exit the loop under the following conditions:
* 1. We have reached the maximum allowed number of attempts
* 2. There are no more candidates in the linked list (ie. `next` is
* null)
* 3. We have seen two candidates of the same family in a row, stop
* happy eyeballs and let the previous attempt go it alone. */
for (int i = 0; i < HAPPY_EYEBALLS_MAX_ATTEMPTS && next && next->ai_family != prev_family; i++) {
/* Launch a worker thread for this address */
int result = launch_worker(context, next);
if (result != STATUS_SUCCESS)
return result;
/* Wait until the delay between attempts times out or we get
* signalled... */
result = os_event_timedwait(context->race_completed_event, HAPPY_EYEBALLS_DELAY_MS);
if (result == 0) {
/* signalled. Break out of the loop. */
break;
} else if (result == EINVAL) {
/* we ran into an error. */
context->error = result;
context->error_message = "happy-eyeballs: Encountered "
"error waiting for "
"race_completed_event";
return STATUS_FAILURE;
}
/* timer timed out, move to the next candidate... */
prev_family = next->ai_family;
next = next->ai_next;
}
os_atomic_store_bool(&context->is_starting, false);
if (happy_eyeballs_try(context) == EAGAIN) {
int active_count = 0;
for (size_t i = 0; i < context->candidates.num; i++)
active_count += (os_event_try(context->candidates.array[i].socket_completed_event) == EAGAIN);
if (active_count == 0 && coalesce_errors(context) == STATUS_SUCCESS)
signal_end(context);
}
return happy_eyeballs_try(context);
}
int happy_eyeballs_try(struct happy_eyeballs_ctx *context)
{
int status = os_event_try(context->race_completed_event);
if (context->error != 0)
return STATUS_FAILURE;
if (status != 0 && status != EAGAIN) {
context->error = status;
context->error_message = strerror(status);
return STATUS_FAILURE;
}
return status;
}
int happy_eyeballs_timedwait_default(struct happy_eyeballs_ctx *context)
{
return happy_eyeballs_timedwait(context, HAPPY_EYEBALLS_CONNECTION_TIMEOUT_MS);
}
int happy_eyeballs_timedwait(struct happy_eyeballs_ctx *context, unsigned long time_in_millis)
{
if (context == NULL)
return STATUS_INVALID_ARGUMENT;
int status = os_event_timedwait(context->race_completed_event, time_in_millis);
if (context->error != 0)
return STATUS_FAILURE;
if (status != 0 && status != ETIMEDOUT) {
context->error = status;
return STATUS_FAILURE;
}
return status;
}
static void *destroy_thread(void *param)
{
struct happy_eyeballs_ctx *context = param;
os_set_thread_name("happy-eyeballs destroy thread");
#ifdef _WIN32
#define SHUT_RDWR SD_BOTH
#else
#define closesocket(s) close(s)
#endif
/* We do not need to lock context->candidate_mutex here because the
* candidate array is _only_ mutated in happy_eyeballs_connect. Using
* this function at the same time as connect is a programmer error.
* Locking it here will cause a deadlock with join.
*
* Shutdown non-winning sockets (but keep the socket alive so that
* things error out in threads) */
for (size_t i = 0; i < context->candidates.num; i++) {
if (context->candidates.array[i].sockfd != INVALID_SOCKET &&
context->candidates.array[i].sockfd != context->socket_fd) {
shutdown(context->candidates.array[i].sockfd, SHUT_RDWR);
}
}
/* Join threads */
for (size_t i = 0; i < context->candidates.num; i++) {
pthread_join(context->candidates.array[i].thread, NULL);
os_event_destroy(context->candidates.array[i].socket_completed_event);
}
/* Close sockets */
for (size_t i = 0; i < context->candidates.num; i++) {
if (context->candidates.array[i].sockfd != INVALID_SOCKET &&
context->candidates.array[i].sockfd != context->socket_fd) {
closesocket(context->candidates.array[i].sockfd);
}
}
pthread_mutex_destroy(&context->winner_mutex);
pthread_mutex_destroy(&context->candidate_mutex);
os_event_destroy(context->race_completed_event);
if (context->addresses != NULL)
freeaddrinfo(context->addresses);
da_free(context->candidates);
free(context);
return NULL;
}
int happy_eyeballs_destroy(struct happy_eyeballs_ctx *context)
{
if (context == NULL)
return STATUS_INVALID_ARGUMENT;
/* The destroy happens asynchronously in another thread due to the
* connect() call blocking on Windows. */
pthread_t thread;
pthread_create(&thread, NULL, destroy_thread, context);
pthread_detach(thread);
return STATUS_SUCCESS;
}
/* ------------------------------------------------------------------------- */
/* Setters & Getters */
int happy_eyeballs_set_bind_addr(struct happy_eyeballs_ctx *context, socklen_t addr_len,
struct sockaddr_storage *addr_storage)
{
if (!context)
return STATUS_INVALID_ARGUMENT;
if (addr_storage && addr_len > 0) {
memcpy(&context->bind_addr, addr_storage, sizeof(struct sockaddr_storage));
context->bind_addr_len = addr_len;
} else {
context->bind_addr_len = 0;
memset(&context->bind_addr, 0, sizeof(struct sockaddr_storage));
}
return STATUS_SUCCESS;
}
SOCKET happy_eyeballs_get_socket_fd(const struct happy_eyeballs_ctx *context)
{
return context ? context->socket_fd : STATUS_INVALID_ARGUMENT;
}
int happy_eyeballs_get_remote_addr(const struct happy_eyeballs_ctx *context, struct sockaddr_storage *addr)
{
if (!context || !addr)
return STATUS_INVALID_ARGUMENT;
if (context->winner_addr_len > 0)
memcpy(addr, &context->winner_addr, context->winner_addr_len);
return context->winner_addr_len;
}
int happy_eyeballs_get_error_code(const struct happy_eyeballs_ctx *context)
{
return context ? context->error : STATUS_INVALID_ARGUMENT;
}
const char *happy_eyeballs_get_error_message(const struct happy_eyeballs_ctx *context)
{
return context ? context->error_message : NULL;
}
uint64_t happy_eyeballs_get_name_resolution_time_ns(const struct happy_eyeballs_ctx *context)
{
return context ? context->name_resolution_time_ns : 0;
}
uint64_t happy_eyeballs_get_connection_time_ns(const struct happy_eyeballs_ctx *context)
{
if (!context || context->connection_time_start > context->connection_time_end)
return 0;
return context->connection_time_end - context->connection_time_start;
}
| 21,889 |
C
|
.c
| 616 | 32.99513 | 107 | 0.707707 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
3,275 |
gl-egl-common.h
|
obsproject_obs-studio/libobs-opengl/gl-egl-common.h
|
#pragma once
#include "gl-nix.h"
#include <glad/glad_egl.h>
const char *gl_egl_error_to_string(EGLint error_number);
struct gs_texture *gl_egl_create_dmabuf_image(EGLDisplay egl_display, unsigned int width, unsigned int height,
uint32_t drm_format, enum gs_color_format color_format, uint32_t n_planes,
const int *fds, const uint32_t *strides, const uint32_t *offsets,
const uint64_t *modifiers);
bool gl_egl_query_dmabuf_capabilities(EGLDisplay egl_display, enum gs_dmabuf_flags *dmabuf_flags, uint32_t **drm_format,
size_t *n_formats);
bool gl_egl_query_dmabuf_modifiers_for_format(EGLDisplay egl_display, uint32_t drm_format, uint64_t **modifiers,
size_t *n_modifiers);
struct gs_texture *gl_egl_create_texture_from_pixmap(EGLDisplay egl_display, uint32_t width, uint32_t height,
enum gs_color_format color_format, EGLint target,
EGLClientBuffer pixmap);
bool gl_egl_enum_adapters(EGLDisplay display, bool (*callback)(void *param, const char *name, uint32_t id),
void *param);
uint32_t gs_get_adapter_count();
| 1,102 |
C
|
.c
| 18 | 55.277778 | 120 | 0.725836 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
3,481 |
obsversion.h
|
obsproject_obs-studio/libobs/obsversion.h
|
#pragma once
extern const char *OBS_VERSION;
extern const char *OBS_VERSION_CANONICAL;
extern const char *OBS_COMMIT;
| 119 |
C
|
.h
| 4 | 28.5 | 41 | 0.815789 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
3,538 |
uthash.h
|
obsproject_obs-studio/libobs/util/uthash.h
|
/******************************************************************************
Copyright (C) 2023 by Dennis Sädtler <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#pragma once
/*
* This file (re)defines various uthash settings for use in libobs
*/
#include <uthash.h>
/* Use OBS allocator */
#undef uthash_malloc
#undef uthash_free
#define uthash_malloc(sz) bmalloc(sz)
#define uthash_free(ptr, sz) bfree(ptr)
/* Use SFH (Super Fast Hash) function instead of JEN */
#undef HASH_FUNCTION
#define HASH_FUNCTION HASH_SFH
| 1,241 |
C
|
.h
| 26 | 44.653846 | 79 | 0.659486 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
3,631 |
amazon-ivs.h
|
obsproject_obs-studio/plugins/rtmp-services/service-specific/amazon-ivs.h
|
#pragma once
#include "service-ingest.h"
extern void amazon_ivs_ingests_lock(void);
extern void amazon_ivs_ingests_unlock(void);
extern size_t amazon_ivs_ingest_count(void);
extern struct ingest amazon_ivs_ingest(size_t idx);
| 228 |
C
|
.h
| 6 | 36.666667 | 51 | 0.804545 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
3,747 |
nv_sdk_versions.h
|
obsproject_obs-studio/plugins/nv-filters/nv_sdk_versions.h
|
#define MIN_VFX_SDK_VERSION (0 << 24 | 7 << 16 | 2 << 8 | 0 << 0)
#define MIN_AFX_SDK_VERSION (1 << 24 | 3 << 16 | 0 << 0)
| 123 |
C
|
.h
| 2 | 60.5 | 65 | 0.512397 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
3,852 |
obs-ffmpeg-output.h
|
obsproject_obs-studio/plugins/obs-ffmpeg/obs-ffmpeg-output.h
|
#pragma once
#include <libavutil/opt.h>
#include <libavutil/pixdesc.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#ifdef NEW_MPEGTS_OUTPUT
#include "obs-ffmpeg-url.h"
#endif
struct ffmpeg_cfg {
const char *url;
const char *format_name;
const char *format_mime_type;
const char *muxer_settings;
const char *protocol_settings; // not used yet for SRT nor RIST
int gop_size;
int video_bitrate;
int audio_bitrate;
const char *video_encoder;
int video_encoder_id;
const char *audio_encoder;
int audio_encoder_id;
int audio_bitrates[MAX_AUDIO_MIXES]; // multi-track
const char *video_settings;
const char *audio_settings;
int audio_mix_count;
int audio_tracks;
const char *audio_stream_names[MAX_AUDIO_MIXES];
enum AVPixelFormat format;
enum AVColorRange color_range;
enum AVColorPrimaries color_primaries;
enum AVColorTransferCharacteristic color_trc;
enum AVColorSpace colorspace;
int max_luminance;
int scale_width;
int scale_height;
int width;
int height;
int frame_size; // audio frame size
const char *username;
const char *password;
const char *stream_id;
const char *encrypt_passphrase;
bool is_srt;
bool is_rist;
};
struct ffmpeg_audio_info {
AVStream *stream;
AVCodecContext *ctx;
};
struct ffmpeg_data {
AVStream *video;
AVCodecContext *video_ctx;
struct ffmpeg_audio_info *audio_infos;
const AVCodec *acodec;
const AVCodec *vcodec;
AVFormatContext *output;
struct SwsContext *swscale;
int64_t total_frames;
AVFrame *vframe;
int frame_size;
uint64_t start_timestamp;
int64_t total_samples[MAX_AUDIO_MIXES];
uint32_t audio_samplerate;
enum audio_format audio_format;
size_t audio_planes;
size_t audio_size;
int num_audio_streams;
/* audio_tracks is a bitmask storing the indices of the mixes */
int audio_tracks;
struct deque excess_frames[MAX_AUDIO_MIXES][MAX_AV_PLANES];
uint8_t *samples[MAX_AUDIO_MIXES][MAX_AV_PLANES];
AVFrame *aframe[MAX_AUDIO_MIXES];
struct ffmpeg_cfg config;
bool initialized;
char *last_error;
};
struct ffmpeg_output {
obs_output_t *output;
volatile bool active;
struct ffmpeg_data ff_data;
bool connecting;
pthread_t start_thread;
uint64_t total_bytes;
uint64_t audio_start_ts;
uint64_t video_start_ts;
uint64_t stop_ts;
volatile bool stopping;
bool write_thread_active;
pthread_mutex_t write_mutex;
pthread_t write_thread;
os_sem_t *write_sem;
os_event_t *stop_event;
DARRAY(AVPacket *) packets;
#ifdef NEW_MPEGTS_OUTPUT
/* used for SRT & RIST */
URLContext *h;
AVIOContext *s;
bool got_headers;
#endif
};
bool ffmpeg_data_init(struct ffmpeg_data *data, struct ffmpeg_cfg *config);
void ffmpeg_data_free(struct ffmpeg_data *data);
| 2,717 |
C
|
.h
| 103 | 24.417476 | 75 | 0.778206 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
3,853 |
obs-ffmpeg-formats.h
|
obsproject_obs-studio/plugins/obs-ffmpeg/obs-ffmpeg-formats.h
|
#pragma once
#include <libavcodec/avcodec.h>
#include <libavutil/pixdesc.h>
static inline int64_t rescale_ts(int64_t val, AVCodecContext *context, AVRational new_base)
{
return av_rescale_q_rnd(val, context->time_base, new_base, AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
}
static inline enum AVPixelFormat obs_to_ffmpeg_video_format(enum video_format format)
{
switch (format) {
case VIDEO_FORMAT_I444:
return AV_PIX_FMT_YUV444P;
case VIDEO_FORMAT_I412:
return AV_PIX_FMT_YUV444P12LE;
case VIDEO_FORMAT_I420:
return AV_PIX_FMT_YUV420P;
case VIDEO_FORMAT_NV12:
return AV_PIX_FMT_NV12;
case VIDEO_FORMAT_YUY2:
return AV_PIX_FMT_YUYV422;
case VIDEO_FORMAT_UYVY:
return AV_PIX_FMT_UYVY422;
case VIDEO_FORMAT_YVYU:
return AV_PIX_FMT_YVYU422;
case VIDEO_FORMAT_RGBA:
return AV_PIX_FMT_RGBA;
case VIDEO_FORMAT_BGRA:
return AV_PIX_FMT_BGRA;
case VIDEO_FORMAT_BGRX:
return AV_PIX_FMT_BGRA;
case VIDEO_FORMAT_Y800:
return AV_PIX_FMT_GRAY8;
case VIDEO_FORMAT_BGR3:
return AV_PIX_FMT_BGR24;
case VIDEO_FORMAT_I422:
return AV_PIX_FMT_YUV422P;
case VIDEO_FORMAT_I210:
return AV_PIX_FMT_YUV422P10LE;
case VIDEO_FORMAT_I40A:
return AV_PIX_FMT_YUVA420P;
case VIDEO_FORMAT_I42A:
return AV_PIX_FMT_YUVA422P;
case VIDEO_FORMAT_YUVA:
return AV_PIX_FMT_YUVA444P;
case VIDEO_FORMAT_YA2L:
return AV_PIX_FMT_YUVA444P12LE;
case VIDEO_FORMAT_I010:
return AV_PIX_FMT_YUV420P10LE;
case VIDEO_FORMAT_P010:
return AV_PIX_FMT_P010LE;
case VIDEO_FORMAT_P216:
return AV_PIX_FMT_P216LE;
case VIDEO_FORMAT_P416:
return AV_PIX_FMT_P416LE;
case VIDEO_FORMAT_NONE:
case VIDEO_FORMAT_AYUV:
default:
return AV_PIX_FMT_NONE;
}
}
static inline enum AVChromaLocation determine_chroma_location(enum AVPixelFormat pix_fmt, enum AVColorSpace colorspace)
{
const AVPixFmtDescriptor *const desc = av_pix_fmt_desc_get(pix_fmt);
if (desc) {
const unsigned log_chroma_w = desc->log2_chroma_w;
const unsigned log_chroma_h = desc->log2_chroma_h;
switch (log_chroma_h) {
case 0:
switch (log_chroma_w) {
case 0:
/* 4:4:4 */
return AVCHROMA_LOC_CENTER;
case 1:
/* 4:2:2 */
return AVCHROMA_LOC_LEFT;
}
break;
case 1:
if (log_chroma_w == 1) {
/* 4:2:0 */
return (colorspace == AVCOL_SPC_BT2020_NCL) ? AVCHROMA_LOC_TOPLEFT : AVCHROMA_LOC_LEFT;
}
}
}
return AVCHROMA_LOC_UNSPECIFIED;
}
static inline enum audio_format convert_ffmpeg_sample_format(enum AVSampleFormat format)
{
switch (format) {
case AV_SAMPLE_FMT_U8:
return AUDIO_FORMAT_U8BIT;
case AV_SAMPLE_FMT_S16:
return AUDIO_FORMAT_16BIT;
case AV_SAMPLE_FMT_S32:
return AUDIO_FORMAT_32BIT;
case AV_SAMPLE_FMT_FLT:
return AUDIO_FORMAT_FLOAT;
case AV_SAMPLE_FMT_U8P:
return AUDIO_FORMAT_U8BIT_PLANAR;
case AV_SAMPLE_FMT_S16P:
return AUDIO_FORMAT_16BIT_PLANAR;
case AV_SAMPLE_FMT_S32P:
return AUDIO_FORMAT_32BIT_PLANAR;
case AV_SAMPLE_FMT_FLTP:
return AUDIO_FORMAT_FLOAT_PLANAR;
default:
return AUDIO_FORMAT_16BIT;
}
/* shouldn't get here */
return AUDIO_FORMAT_16BIT;
}
| 3,038 |
C
|
.h
| 111 | 24.810811 | 119 | 0.750685 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
3,854 |
vaapi-utils.h
|
obsproject_obs-studio/plugins/obs-ffmpeg/vaapi-utils.h
|
// SPDX-FileCopyrightText: 2022 tytan652 <[email protected]>
//
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <util/base.h>
#include <va/va.h>
VADisplay vaapi_open_device(int *fd, const char *device_path, const char *func_name);
void vaapi_close_device(int *fd, VADisplay dpy);
bool vaapi_device_rc_supported(VAProfile profile, VADisplay dpy, uint32_t rc, const char *device_path);
bool vaapi_device_bframe_supported(VAProfile profile, VADisplay dpy);
bool vaapi_display_h264_supported(VADisplay dpy, const char *device_path);
bool vaapi_device_h264_supported(const char *device_path);
const char *vaapi_get_h264_default_device(void);
bool vaapi_display_av1_supported(VADisplay dpy, const char *device_path);
bool vaapi_device_av1_supported(const char *device_path);
const char *vaapi_get_av1_default_device(void);
#ifdef ENABLE_HEVC
bool vaapi_display_hevc_supported(VADisplay dpy, const char *device_path);
bool vaapi_device_hevc_supported(const char *device_path);
const char *vaapi_get_hevc_default_device(void);
#endif
| 1,057 |
C
|
.h
| 21 | 48.952381 | 103 | 0.794747 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
3,857 |
obs-ffmpeg-rist.h
|
obsproject_obs-studio/plugins/obs-ffmpeg/obs-ffmpeg-rist.h
|
/*
* The following code is a port of FFmpeg/avformat/librist.c for obs-studio.
* Port by [email protected].
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
#include <obs-module.h>
#include "obs-ffmpeg-url.h"
#include <librist/librist.h>
#include <librist/version.h>
// RIST_MAX_PACKET_SIZE - 28 minimum protocol overhead
#define RIST_MAX_PAYLOAD_SIZE (10000 - 28)
#define FF_LIBRIST_MAKE_VERSION(major, minor, patch) ((patch) + ((minor) * 0x100) + ((major) * 0x10000))
#define FF_LIBRIST_VERSION \
FF_LIBRIST_MAKE_VERSION(LIBRIST_API_VERSION_MAJOR, LIBRIST_API_VERSION_MINOR, LIBRIST_API_VERSION_PATCH)
#define FF_LIBRIST_VERSION_41 FF_LIBRIST_MAKE_VERSION(4, 1, 0)
#define FF_LIBRIST_VERSION_42 FF_LIBRIST_MAKE_VERSION(4, 2, 0)
#define FF_LIBRIST_FIFO_DEFAULT_SHIFT 13
typedef struct RISTContext {
int profile;
int buffer_size;
int packet_size;
int log_level;
int encryption;
int fifo_shift;
bool overrun_nonfatal;
char *secret;
char *username;
char *password;
struct rist_logging_settings logging_settings;
struct rist_peer_config peer_config;
struct rist_peer *peer;
struct rist_ctx *ctx;
int statsinterval;
struct rist_stats_sender_peer *stats_list;
} RISTContext;
static int risterr2ret(int err)
{
switch (err) {
case RIST_ERR_MALLOC:
return AVERROR(ENOMEM);
default:
return AVERROR_EXTERNAL;
}
}
static int log_cb(void *arg, enum rist_log_level log_level, const char *msg)
{
int level;
switch (log_level) {
case RIST_LOG_ERROR:
level = AV_LOG_ERROR;
break;
case RIST_LOG_WARN:
level = AV_LOG_WARNING;
break;
case RIST_LOG_NOTICE:
level = AV_LOG_INFO;
break;
case RIST_LOG_INFO:
level = AV_LOG_VERBOSE;
break;
case RIST_LOG_DEBUG:
level = AV_LOG_DEBUG;
break;
case RIST_LOG_DISABLE:
level = AV_LOG_QUIET;
break;
default:
level = AV_LOG_WARNING;
}
av_log(arg, level, "%s", msg);
return 0;
}
static int librist_close(URLContext *h)
{
RISTContext *s = h->priv_data;
int ret = 0;
if (s->secret)
bfree(s->secret);
if (s->username)
bfree(s->username);
if (s->password)
bfree(s->password);
s->peer = NULL;
if (s->ctx)
ret = rist_destroy(s->ctx);
if (ret < 0) {
blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / librist]: Failed to close properly %s", h->url);
return -1;
}
s->ctx = NULL;
return 0;
}
static int cb_stats(void *arg, const struct rist_stats *stats_container)
{
RISTContext *s = (RISTContext *)arg;
rist_log(&s->logging_settings, RIST_LOG_INFO, "%s\n", stats_container->stats_json);
if (stats_container->stats_type == RIST_STATS_SENDER_PEER) {
blog(LOG_INFO, "---------------------------------");
blog(LOG_DEBUG,
"[obs-ffmpeg mpegts muxer / librist]: Session Summary\n"
"\tbandwidth [%.3f Mbps]\n"
"\tpackets sent [%" PRIu64 "]\n"
"\tpkts received [%" PRIu64 "]\n"
"\tpkts retransmitted [%" PRIu64 "]\n"
"\tquality (pkt sent over sent+retransmitted+skipped) [%.2f]\n"
"\trtt [%" PRIu32 " ms]\n",
(double)(stats_container->stats.sender_peer.bandwidth) / 1000000.0,
stats_container->stats.sender_peer.sent, stats_container->stats.sender_peer.received,
stats_container->stats.sender_peer.retransmitted, stats_container->stats.sender_peer.quality,
stats_container->stats.sender_peer.rtt);
}
rist_stats_free(stats_container);
return 0;
}
static int librist_open(URLContext *h, const char *uri)
{
RISTContext *s = h->priv_data;
struct rist_logging_settings *logging_settings = &s->logging_settings;
struct rist_peer_config *peer_config = &s->peer_config;
int ret;
s->buffer_size = 3000;
s->profile = RIST_PROFILE_MAIN;
s->packet_size = 1316;
s->log_level = RIST_LOG_INFO;
s->encryption = 0;
s->overrun_nonfatal = 0;
s->fifo_shift = FF_LIBRIST_FIFO_DEFAULT_SHIFT;
s->logging_settings = (struct rist_logging_settings)LOGGING_SETTINGS_INITIALIZER;
s->statsinterval = 60000; // log stats every 60 seconds
ret = rist_logging_set(&logging_settings, s->log_level, log_cb, h, NULL, NULL);
if (ret < 0) {
blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / librist]: Failed to initialize logging settings");
return OBS_OUTPUT_CONNECT_FAILED;
}
blog(LOG_INFO, "[obs-ffmpeg mpegts muxer / librist]: libRIST version: %s, API: %s", librist_version(),
librist_api_version());
h->max_packet_size = s->packet_size;
ret = rist_sender_create(&s->ctx, s->profile, 0, logging_settings);
if (ret < 0) {
blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / librist]: Failed to create a sender");
goto err;
}
ret = rist_peer_config_defaults_set(peer_config);
if (ret < 0) {
blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / librist]: Failed to set peer config defaults");
goto err;
}
#if FF_LIBRIST_VERSION < FF_LIBRIST_VERSION_41
ret = rist_parse_address(uri, (const struct rist_peer_config **)&peer_config);
#else
ret = rist_parse_address2(uri, &peer_config);
#endif
if (ret < 0) {
blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / librist]: Failed to parse url: %s", uri);
librist_close(h);
return OBS_OUTPUT_INVALID_STREAM;
}
if (((s->encryption == 128 || s->encryption == 256) && !s->secret) ||
((peer_config->key_size == 128 || peer_config->key_size == 256) && !peer_config->secret[0])) {
blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / librist]: Secret is mandatory if encryption is enabled");
librist_close(h);
return OBS_OUTPUT_INVALID_STREAM;
}
if (s->secret && peer_config->secret[0] == 0)
av_strlcpy(peer_config->secret, s->secret, RIST_MAX_STRING_SHORT);
if (s->secret && (s->encryption == 128 || s->encryption == 256))
peer_config->key_size = s->encryption;
if (s->buffer_size) {
peer_config->recovery_length_min = s->buffer_size;
peer_config->recovery_length_max = s->buffer_size;
}
if (s->username && peer_config->srp_username[0] == 0)
av_strlcpy(peer_config->srp_username, s->username, RIST_MAX_STRING_LONG);
if (s->password && peer_config->srp_password[0] == 0)
av_strlcpy(peer_config->srp_password, s->password, RIST_MAX_STRING_LONG);
ret = rist_peer_create(s->ctx, &s->peer, &s->peer_config);
if (ret < 0) {
blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / librist]: Failed to create a peer.");
goto err;
}
ret = rist_start(s->ctx);
if (ret < 0) {
blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / librist]: RIST failed to start");
goto err;
}
if (rist_stats_callback_set(s->ctx, s->statsinterval, cb_stats, (void *)s) == -1)
rist_log(&s->logging_settings, RIST_LOG_ERROR, "Could not enable stats callback");
return 0;
err:
librist_close(h);
return OBS_OUTPUT_CONNECT_FAILED;
}
static int librist_write(URLContext *h, const uint8_t *buf, int size)
{
RISTContext *s = h->priv_data;
struct rist_data_block data_block = {0};
int ret;
data_block.ts_ntp = 0;
data_block.payload = buf;
data_block.payload_len = size;
ret = rist_sender_data_write(s->ctx, &data_block);
if (ret < 0) {
blog(LOG_WARNING, "[obs-ffmpeg mpegts muxer / librist]: Failed to send %i bytes", size);
return risterr2ret(ret);
}
return ret;
}
| 7,684 |
C
|
.h
| 219 | 32.538813 | 105 | 0.704481 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
3,862 |
rtmp-av1.h
|
obsproject_obs-studio/plugins/obs-outputs/rtmp-av1.h
|
/******************************************************************************
Copyright (C) 2023 by Lain Bailey <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#pragma once
#include <stdint.h>
#include <stddef.h>
struct encoder_packet;
extern void obs_parse_av1_packet(struct encoder_packet *avc_packet, const struct encoder_packet *src);
extern size_t obs_parse_av1_header(uint8_t **header, const uint8_t *data, size_t size);
| 1,144 |
C
|
.h
| 19 | 56.526316 | 102 | 0.654741 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
3,864 |
utils.h
|
obsproject_obs-studio/plugins/obs-outputs/utils.h
|
#pragma once
#if defined(__GNUC__) || defined(__clang__)
static inline uint32_t clz32(unsigned long val)
{
return __builtin_clz(val);
}
static inline uint32_t ctz32(unsigned long val)
{
return __builtin_ctz(val);
}
#elif defined(_MSC_VER) && _MSC_VER >= 1400
static inline uint32_t clz32(unsigned long val)
{
/* __lzcnt() / _lzcnt_u32() do not work correctly on older Intel CPUs,
* so use BSR instead for better compatibility. */
uint32_t zeros = 0;
_BitScanReverse(&zeros, val);
return 31 - zeros;
}
static inline uint32_t ctz32(unsigned long val)
{
return _tzcnt_u32(val);
}
#else
static uint32_t popcnt(uint32_t x)
{
x -= ((x >> 1) & 0x55555555);
x = (((x >> 2) & 0x33333333) + (x & 0x33333333));
x = (((x >> 4) + x) & 0x0f0f0f0f);
x += (x >> 8);
x += (x >> 16);
return x & 0x0000003f;
}
static uint32_t clz32(uint32_t x)
{
x |= (x >> 1);
x |= (x >> 2);
x |= (x >> 4);
x |= (x >> 8);
x |= (x >> 16);
return 32 - popcnt(x);
}
static uint32_t ctz32(uint32_t x)
{
return popcnt((x & -x) - 1);
}
#endif
static inline uint32_t min_u32(uint32_t a, uint32_t b)
{
return (a < b) ? a : b;
}
static inline uint16_t min_u16(uint16_t a, uint16_t b)
{
return (a < b) ? a : b;
}
static inline int32_t min_i32(int32_t a, int32_t b)
{
return (a < b) ? a : b;
}
static inline uint8_t max_u8(uint8_t a, uint8_t b)
{
return (a > b) ? a : b;
}
| 1,362 |
C
|
.h
| 63 | 20.063492 | 71 | 0.628682 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
3,865 |
flv-mux.h
|
obsproject_obs-studio/plugins/obs-outputs/flv-mux.h
|
/******************************************************************************
Copyright (C) 2023 by Lain Bailey <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#pragma once
#include <obs.h>
#define MILLISECOND_DEN 1000
enum audio_id_t {
AUDIO_CODEC_NONE = 0,
AUDIO_CODEC_AAC = 1,
};
enum video_id_t {
CODEC_NONE = 0, // not valid in rtmp
CODEC_H264 = 1, // legacy & Y2023 spec
CODEC_AV1, // Y2023 spec
CODEC_HEVC,
};
static enum audio_id_t to_audio_type(const char *codec)
{
if (strcmp(codec, "aac") == 0)
return AUDIO_CODEC_AAC;
return AUDIO_CODEC_NONE;
}
static enum video_id_t to_video_type(const char *codec)
{
if (strcmp(codec, "h264") == 0)
return CODEC_H264;
if (strcmp(codec, "av1") == 0)
return CODEC_AV1;
#ifdef ENABLE_HEVC
if (strcmp(codec, "hevc") == 0)
return CODEC_HEVC;
#endif
return 0;
}
static int32_t get_ms_time(struct encoder_packet *packet, int64_t val)
{
return (int32_t)(val * MILLISECOND_DEN / packet->timebase_den);
}
extern void write_file_info(FILE *file, int64_t duration_ms, int64_t size);
extern void flv_meta_data(obs_output_t *context, uint8_t **output, size_t *size, bool write_header);
extern void flv_packet_mux(struct encoder_packet *packet, int32_t dts_offset, uint8_t **output, size_t *size,
bool is_header);
// Y2023 spec
extern void flv_packet_start(struct encoder_packet *packet, enum video_id_t codec, uint8_t **output, size_t *size,
size_t idx);
extern void flv_packet_frames(struct encoder_packet *packet, enum video_id_t codec, int32_t dts_offset,
uint8_t **output, size_t *size, size_t idx);
extern void flv_packet_end(struct encoder_packet *packet, enum video_id_t codec, uint8_t **output, size_t *size,
size_t idx);
extern void flv_packet_metadata(enum video_id_t codec, uint8_t **output, size_t *size, int bits_per_raw_sample,
uint8_t color_primaries, int color_trc, int color_space, int min_luminance,
int max_luminance, size_t idx);
extern void flv_packet_audio_start(struct encoder_packet *packet, enum audio_id_t codec, uint8_t **output, size_t *size,
size_t idx);
extern void flv_packet_audio_frames(struct encoder_packet *packet, enum audio_id_t codec, int32_t dts_offset,
uint8_t **output, size_t *size, size_t idx);
| 2,974 |
C
|
.h
| 66 | 42.090909 | 120 | 0.685665 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
3,868 |
rtmp-stream.h
|
obsproject_obs-studio/plugins/obs-outputs/rtmp-stream.h
|
#include <obs-module.h>
#include <util/platform.h>
#include <util/deque.h>
#include <util/dstr.h>
#include <util/threading.h>
#include <inttypes.h>
#include "librtmp/rtmp.h"
#include "librtmp/log.h"
#include "flv-mux.h"
#include "net-if.h"
#ifdef _WIN32
#include <Iphlpapi.h>
#else
#include <sys/ioctl.h>
#endif
#define do_log(level, format, ...) \
blog(level, "[rtmp stream: '%s'] " format, obs_output_get_name(stream->output), ##__VA_ARGS__)
#define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
#define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
#define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
#define OPT_DYN_BITRATE "dyn_bitrate"
#define OPT_DROP_THRESHOLD "drop_threshold_ms"
#define OPT_PFRAME_DROP_THRESHOLD "pframe_drop_threshold_ms"
#define OPT_MAX_SHUTDOWN_TIME_SEC "max_shutdown_time_sec"
#define OPT_BIND_IP "bind_ip"
#define OPT_IP_FAMILY "ip_family"
#define OPT_NEWSOCKETLOOP_ENABLED "new_socket_loop_enabled"
#define OPT_LOWLATENCY_ENABLED "low_latency_mode_enabled"
#define OPT_METADATA_MULTITRACK "metadata_multitrack"
//#define TEST_FRAMEDROPS
//#define TEST_FRAMEDROPS_WITH_BITRATE_SHORTCUTS
#ifdef TEST_FRAMEDROPS
#define DROPTEST_MAX_KBPS 3000
#define DROPTEST_MAX_BYTES (DROPTEST_MAX_KBPS * 1000 / 8)
struct droptest_info {
uint64_t ts;
size_t size;
};
#endif
struct dbr_frame {
uint64_t send_beg;
uint64_t send_end;
size_t size;
};
struct rtmp_stream {
obs_output_t *output;
pthread_mutex_t packets_mutex;
struct deque packets;
bool sent_headers;
bool got_first_packet;
int64_t start_dts_offset;
volatile bool connecting;
pthread_t connect_thread;
volatile bool active;
volatile bool disconnected;
volatile bool encode_error;
pthread_t send_thread;
int max_shutdown_time_sec;
os_sem_t *send_sem;
os_event_t *stop_event;
uint64_t stop_ts;
uint64_t shutdown_timeout_ts;
struct dstr path, key;
struct dstr username, password;
struct dstr encoder_name;
struct dstr bind_ip;
socklen_t addrlen_hint; /* hint IPv4 vs IPv6 */
/* frame drop variables */
int64_t drop_threshold_usec;
int64_t pframe_drop_threshold_usec;
int min_priority;
float congestion;
int64_t last_dts_usec;
uint64_t total_bytes_sent;
int dropped_frames;
#ifdef TEST_FRAMEDROPS
struct deque droptest_info;
uint64_t droptest_last_key_check;
size_t droptest_max;
size_t droptest_size;
#endif
pthread_mutex_t dbr_mutex;
struct deque dbr_frames;
size_t dbr_data_size;
uint64_t dbr_inc_timeout;
long audio_bitrate;
long dbr_est_bitrate;
long dbr_orig_bitrate;
long dbr_prev_bitrate;
long dbr_cur_bitrate;
long dbr_inc_bitrate;
bool dbr_enabled;
enum audio_id_t audio_codec[MAX_OUTPUT_AUDIO_ENCODERS];
enum video_id_t video_codec[MAX_OUTPUT_VIDEO_ENCODERS];
RTMP rtmp;
bool new_socket_loop;
bool low_latency_mode;
bool disable_send_window_optimization;
bool socket_thread_active;
pthread_t socket_thread;
uint8_t *write_buf;
size_t write_buf_len;
size_t write_buf_size;
pthread_mutex_t write_buf_mutex;
os_event_t *buffer_space_available_event;
os_event_t *buffer_has_data_event;
os_event_t *socket_available_event;
os_event_t *send_thread_signaled_exit;
};
#ifdef _WIN32
void *socket_thread_windows(void *data);
#endif
/* Adapted from FFmpeg's libavutil/pixfmt.h
*
* Renamed to make it apparent that these are not imported as this module does
* not use or link against FFmpeg.
*/
/**
* Chromaticity coordinates of the source primaries.
* These values match the ones defined by ISO/IEC 23091-2_2019 subclause 8.1 and ITU-T H.273.
*/
enum OBSColorPrimaries {
OBSCOL_PRI_RESERVED0 = 0,
OBSCOL_PRI_BT709 = 1, ///< also ITU-R BT1361 / IEC 61966-2-4 / SMPTE RP 177 Annex B
OBSCOL_PRI_UNSPECIFIED = 2,
OBSCOL_PRI_RESERVED = 3,
OBSCOL_PRI_BT470M = 4, ///< also FCC Title 47 Code of Federal Regulations 73.682 (a)(20)
OBSCOL_PRI_BT470BG = 5, ///< also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM
OBSCOL_PRI_SMPTE170M = 6, ///< also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC
OBSCOL_PRI_SMPTE240M = 7, ///< identical to above, also called "SMPTE C" even though it uses D65
OBSCOL_PRI_FILM = 8, ///< colour filters using Illuminant C
OBSCOL_PRI_BT2020 = 9, ///< ITU-R BT2020
OBSCOL_PRI_SMPTE428 = 10, ///< SMPTE ST 428-1 (CIE 1931 XYZ)
OBSCOL_PRI_SMPTEST428_1 = OBSCOL_PRI_SMPTE428,
OBSCOL_PRI_SMPTE431 = 11, ///< SMPTE ST 431-2 (2011) / DCI P3
OBSCOL_PRI_SMPTE432 = 12, ///< SMPTE ST 432-1 (2010) / P3 D65 / Display P3
OBSCOL_PRI_EBU3213 = 22, ///< EBU Tech. 3213-E (nothing there) / one of JEDEC P22 group phosphors
OBSCOL_PRI_JEDEC_P22 = OBSCOL_PRI_EBU3213,
OBSCOL_PRI_NB ///< Not part of ABI
};
/**
* Color Transfer Characteristic.
* These values match the ones defined by ISO/IEC 23091-2_2019 subclause 8.2.
*/
enum OBSColorTransferCharacteristic {
OBSCOL_TRC_RESERVED0 = 0,
OBSCOL_TRC_BT709 = 1, ///< also ITU-R BT1361
OBSCOL_TRC_UNSPECIFIED = 2,
OBSCOL_TRC_RESERVED = 3,
OBSCOL_TRC_GAMMA22 = 4, ///< also ITU-R BT470M / ITU-R BT1700 625 PAL & SECAM
OBSCOL_TRC_GAMMA28 = 5, ///< also ITU-R BT470BG
OBSCOL_TRC_SMPTE170M = 6, ///< also ITU-R BT601-6 525 or 625 / ITU-R BT1358 525 or 625 / ITU-R BT1700 NTSC
OBSCOL_TRC_SMPTE240M = 7,
OBSCOL_TRC_LINEAR = 8, ///< "Linear transfer characteristics"
OBSCOL_TRC_LOG = 9, ///< "Logarithmic transfer characteristic (100:1 range)"
OBSCOL_TRC_LOG_SQRT = 10, ///< "Logarithmic transfer characteristic (100 * Sqrt(10) : 1 range)"
OBSCOL_TRC_IEC61966_2_4 = 11, ///< IEC 61966-2-4
OBSCOL_TRC_BT1361_ECG = 12, ///< ITU-R BT1361 Extended Colour Gamut
OBSCOL_TRC_IEC61966_2_1 = 13, ///< IEC 61966-2-1 (sRGB or sYCC)
OBSCOL_TRC_BT2020_10 = 14, ///< ITU-R BT2020 for 10-bit system
OBSCOL_TRC_BT2020_12 = 15, ///< ITU-R BT2020 for 12-bit system
OBSCOL_TRC_SMPTE2084 = 16, ///< SMPTE ST 2084 for 10-, 12-, 14- and 16-bit systems
OBSCOL_TRC_SMPTEST2084 = OBSCOL_TRC_SMPTE2084,
OBSCOL_TRC_SMPTE428 = 17, ///< SMPTE ST 428-1
OBSCOL_TRC_SMPTEST428_1 = OBSCOL_TRC_SMPTE428,
OBSCOL_TRC_ARIB_STD_B67 = 18, ///< ARIB STD-B67, known as "Hybrid log-gamma"
OBSCOL_TRC_NB ///< Not part of ABI
};
/**
* YUV colorspace type.
* These values match the ones defined by ISO/IEC 23091-2_2019 subclause 8.3.
*/
enum OBSColorSpace {
OBSCOL_SPC_RGB = 0, ///< order of coefficients is actually GBR, also IEC 61966-2-1 (sRGB), YZX and ST 428-1
OBSCOL_SPC_BT709 = 1, ///< also ITU-R BT1361 / IEC 61966-2-4 xvYCC709 / derived in SMPTE RP 177 Annex B
OBSCOL_SPC_UNSPECIFIED = 2,
OBSCOL_SPC_RESERVED = 3, ///< reserved for future use by ITU-T and ISO/IEC just like 15-255 are
OBSCOL_SPC_FCC = 4, ///< FCC Title 47 Code of Federal Regulations 73.682 (a)(20)
OBSCOL_SPC_BT470BG =
5, ///< also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM / IEC 61966-2-4 xvYCC601
OBSCOL_SPC_SMPTE170M =
6, ///< also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC / functionally identical to above
OBSCOL_SPC_SMPTE240M =
7, ///< derived from 170M primaries and D65 white point, 170M is derived from BT470 System M's primaries
OBSCOL_SPC_YCGCO = 8, ///< used by Dirac / VC-2 and H.264 FRext, see ITU-T SG16
OBSCOL_SPC_YCOCG = OBSCOL_SPC_YCGCO,
OBSCOL_SPC_BT2020_NCL = 9, ///< ITU-R BT2020 non-constant luminance system
OBSCOL_SPC_BT2020_CL = 10, ///< ITU-R BT2020 constant luminance system
OBSCOL_SPC_SMPTE2085 = 11, ///< SMPTE 2085, Y'D'zD'x
OBSCOL_SPC_CHROMA_DERIVED_NCL = 12, ///< Chromaticity-derived non-constant luminance system
OBSCOL_SPC_CHROMA_DERIVED_CL = 13, ///< Chromaticity-derived constant luminance system
OBSCOL_SPC_ICTCP = 14, ///< ITU-R BT.2100-0, ICtCp
OBSCOL_SPC_NB ///< Not part of ABI
};
| 7,796 |
C
|
.h
| 194 | 38.283505 | 110 | 0.715927 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
3,869 |
mp4-mux-internal.h
|
obsproject_obs-studio/plugins/obs-outputs/mp4-mux-internal.h
|
/******************************************************************************
Copyright (C) 2024 by Dennis Sädtler <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#pragma once
#include "mp4-mux.h"
#include <util/darray.h>
#include <util/deque.h>
#include <util/serializer.h>
/* Flavour for target compatibility */
enum mp4_flavour {
MP4, /* ISO/IEC 14496-12 */
MOV, /* Apple QuickTime */
CMAF, /* ISO/IEC 23000-19 */
};
enum mp4_track_type {
TRACK_UNKNOWN,
TRACK_VIDEO,
TRACK_AUDIO,
TRACK_CHAPTERS,
};
enum mp4_codec {
CODEC_UNKNOWN,
/* Video Codecs */
CODEC_H264,
CODEC_HEVC,
CODEC_AV1,
/* Audio Codecs */
CODEC_AAC,
CODEC_OPUS,
CODEC_FLAC,
CODEC_ALAC,
CODEC_PCM_I16,
CODEC_PCM_I24,
CODEC_PCM_F32,
/* Text/Chapter trakcs */
CODEC_TEXT,
};
struct chunk {
uint64_t offset;
uint32_t size;
uint32_t samples;
};
struct sample_delta {
uint32_t count;
uint32_t delta;
};
struct sample_offset {
uint32_t count;
int32_t offset;
};
struct fragment_sample {
uint32_t size;
int32_t offset;
uint32_t duration;
};
struct mp4_track {
enum mp4_track_type type;
enum mp4_codec codec;
/* Track ID in container */
uint8_t track_id;
/* Number of samples for this track */
uint64_t samples;
/* Duration for this track */
uint64_t duration;
/* Encoder associated with this track */
obs_encoder_t *encoder;
/* Time Base (1/FPS for video, 1/sample rate for audio) */
uint32_t timebase_num;
uint32_t timebase_den;
/* Output timescale calculated from time base (Video only) */
uint32_t timescale;
/* First PTS this track has seen (in track timescale) */
int64_t first_pts;
/* Highest PTS this track has seen (in usec) */
int64_t last_pts_usec;
/* deque of encoder_packet belonging to this track */
struct deque packets;
/* Sample sizes (fixed for PCM) */
uint32_t sample_size;
DARRAY(uint32_t) sample_sizes;
/* Data chunks in file containing samples for this track */
DARRAY(struct chunk) chunks;
/* Time delta between samples */
DARRAY(struct sample_delta) deltas;
/* Sample CT-DT offset, i.e. DTS-PTS offset (Video only) */
bool needs_ctts;
int32_t dts_offset;
DARRAY(struct sample_offset) offsets;
/* Sync samples, i.e. keyframes (Video only) */
DARRAY(uint32_t) sync_samples;
/* Temporary array with information about the samples to be included
* in the next fragment. */
DARRAY(struct fragment_sample) fragment_samples;
};
struct mp4_mux {
obs_output_t *output;
struct serializer *serializer;
/* Target format compatibility */
enum mp4_flavour mode;
/* Flags */
enum mp4_mux_flags flags;
uint32_t fragments_written;
/* PTS where next fragmentation should take place */
int64_t next_frag_pts;
/* Creation time (seconds since Jan 1 1904) */
uint64_t creation_time;
/* Offset of placeholder atom/box to contain final mdat header */
size_t placeholder_offset;
uint8_t track_ctr;
/* Audio/Video tracks */
DARRAY(struct mp4_track) tracks;
/* Special tracks */
struct mp4_track *chapter_track;
};
/* clang-format off */
// Defined in ISO/IEC 14496-12:2015 Section 8.2.2.1
const int32_t UNITY_MATRIX[9] = {
0x00010000, 0, 0,
0, 0x00010000, 0,
0, 0, 0x40000000
};
/* clang-format on */
enum tfhd_flags {
BASE_DATA_OFFSET_PRESENT = 0x000001,
SAMPLE_DESCRIPTION_INDEX_PRESENT = 0x000002,
DEFAULT_SAMPLE_DURATION_PRESENT = 0x000008,
DEFAULT_SAMPLE_SIZE_PRESENT = 0x000010,
DEFAULT_SAMPLE_FLAGS_PRESENT = 0x000020,
DURATION_IS_EMPTY = 0x010000,
DEFAULT_BASE_IS_MOOF = 0x020000,
};
enum trun_flags {
DATA_OFFSET_PRESENT = 0x000001,
FIRST_SAMPLE_FLAGS_PRESENT = 0x000004,
SAMPLE_DURATION_PRESENT = 0x000100,
SAMPLE_SIZE_PRESENT = 0x000200,
SAMPLE_FLAGS_PRESENT = 0x000400,
SAMPLE_COMPOSITION_TIME_OFFSETS_PRESENT = 0x000800,
};
/*
* ISO Standard structure (big endian so we can't easily use it):
*
* struct sample_flags {
* uint32_t reserved : 4;
* uint32_t is_leading : 2;
* uint32_t sample_depends_on : 2;
* uint32_t sample_is_depended_on : 2;
* uint32_t sample_has_redundancy : 2;
* uint32_t sample_padding_value : 3;
* uint32_t sample_is_non_sync_sample : 1;
* uint32_t sample_degradation_priority : 16;
};
*/
enum sample_flags {
SAMPLE_FLAG_IS_NON_SYNC = 0x00010000,
SAMPLE_FLAG_DEPENDS_YES = 0x01000000,
SAMPLE_FLAG_DEPENDS_NO = 0x02000000,
};
#ifndef _WIN32
static inline size_t min(size_t a, size_t b)
{
return a < b ? a : b;
}
#endif
static inline void get_speaker_positions(enum speaker_layout layout, uint8_t *arr, uint8_t *size, uint8_t *iso_layout)
{
switch (layout) {
case SPEAKERS_MONO:
arr[0] = 2; // FC
*size = 1;
*iso_layout = 1;
break;
case SPEAKERS_UNKNOWN:
case SPEAKERS_STEREO:
arr[0] = 0; // FL
arr[1] = 1; // FR
*size = 2;
*iso_layout = 2;
break;
case SPEAKERS_2POINT1:
arr[0] = 0; // FL
arr[1] = 1; // FR
arr[2] = 3; // LFE
*size = 3;
break;
case SPEAKERS_4POINT0:
arr[0] = 0; // FL
arr[1] = 1; // FR
arr[2] = 2; // FC
arr[3] = 10; // RC
*size = 4;
*iso_layout = 4;
break;
case SPEAKERS_4POINT1:
arr[0] = 0; // FL
arr[1] = 1; // FR
arr[2] = 2; // FC
arr[3] = 3; // LFE
arr[4] = 10; // RC
*size = 5;
break;
case SPEAKERS_5POINT1:
arr[0] = 0; // FL
arr[1] = 1; // FR
arr[2] = 2; // FC
arr[3] = 3; // LFE
arr[4] = 8; // RL
arr[5] = 9; // RR
*size = 6;
break;
case SPEAKERS_7POINT1:
arr[0] = 0; // FL
arr[1] = 1; // FR
arr[2] = 2; // FC
arr[3] = 3; // LFE
arr[4] = 8; // RL
arr[5] = 9; // RR
arr[6] = 13; // SL
arr[7] = 14; // SR
*size = 8;
*iso_layout = 12;
break;
}
}
static inline void get_colour_information(obs_encoder_t *enc, uint16_t *pri, uint16_t *trc, uint16_t *spc,
uint8_t *full_range)
{
video_t *video = obs_encoder_video(enc);
const struct video_output_info *info = video_output_get_info(video);
*full_range = info->range == VIDEO_RANGE_FULL ? 1 : 0;
switch (info->colorspace) {
case VIDEO_CS_601:
*pri = 6; // OBSCOL_PRI_SMPTE170M
*trc = 6;
*spc = 6;
break;
case VIDEO_CS_DEFAULT:
case VIDEO_CS_709:
*pri = 1; // OBSCOL_PRI_BT709
*trc = 1;
*spc = 1;
break;
case VIDEO_CS_SRGB:
*pri = 1; // OBSCOL_PRI_BT709
*trc = 13; // OBSCOL_TRC_IEC61966_2_1
*spc = 1; // OBSCOL_PRI_BT709
break;
case VIDEO_CS_2100_PQ:
*pri = 9; // OBSCOL_PRI_BT2020
*trc = 16; // OBSCOL_TRC_SMPTE2084
*spc = 9; // OBSCOL_SPC_BT2020_NCL
break;
case VIDEO_CS_2100_HLG:
*pri = 9; // OBSCOL_PRI_BT2020
*trc = 18; // OBSCOL_TRC_ARIB_STD_B67
*spc = 9; // OBSCOL_SPC_BT2020_NCL
}
}
/* Chapter stubs (from libavformat/movenc.c) */
static const uint8_t TEXT_STUB_HEADER[] = {
// TextSampleEntry
0x00, 0x00, 0x00, 0x01, // displayFlags
0x00, 0x00, // horizontal + vertical justification
0x00, 0x00, 0x00, 0x00, // bgColourRed/Green/Blue/Alpha
// BoxRecord
0x00, 0x00, 0x00, 0x00, // defTextBoxTop/Left
0x00, 0x00, 0x00, 0x00, // defTextBoxBottom/Right
// StyleRecord
0x00, 0x00, 0x00, 0x00, // startChar + endChar
0x00, 0x01, // fontID
0x00, 0x00, // fontStyleFlags + fontSize
0x00, 0x00, 0x00, 0x00, // fgColourRed/Green/Blue/Alpha
// FontTableBox
0x00, 0x00, 0x00, 0x0D, // box size
'f', 't', 'a', 'b', // box atom name
0x00, 0x01, // entry count
// FontRecord
0x00, 0x01, // font ID
0x00, // font name length
};
/* clang-format off */
static const char CHAPTER_PKT_FOOTER[12] = {
0x00, 0x00, 0x00, 0x0C,
'e', 'n', 'c', 'd',
0x00, 0x00, 0x01, 0x00
};
/* clang-format on */
| 8,185 |
C
|
.h
| 297 | 25.245791 | 118 | 0.667219 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
3,870 |
mp4-mux.h
|
obsproject_obs-studio/plugins/obs-outputs/mp4-mux.h
|
/******************************************************************************
Copyright (C) 2024 by Dennis Sädtler <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#pragma once
#include <obs.h>
#include <util/serializer.h>
struct mp4_mux;
enum mp4_mux_flags {
/* Uses mdta key/value list for metadata instead of QuickTime keys */
MP4_USE_MDTA_KEY_VALUE = 1 << 0,
/* Write encoder configuration to trak udat */
MP4_WRITE_ENCODER_INFO = 1 << 1,
/* Skip "soft-remux" and leave file in fragmented state */
MP4_SKIP_FINALISATION = 1 << 2,
/* Use negative CTS instead of edit lists */
MP4_USE_NEGATIVE_CTS = 1 << 3,
};
struct mp4_mux *mp4_mux_create(obs_output_t *output, struct serializer *serializer, enum mp4_mux_flags flags);
void mp4_mux_destroy(struct mp4_mux *mux);
bool mp4_mux_submit_packet(struct mp4_mux *mux, struct encoder_packet *pkt);
bool mp4_mux_add_chapter(struct mp4_mux *mux, int64_t dts_usec, const char *name);
bool mp4_mux_finalise(struct mp4_mux *mux);
| 1,699 |
C
|
.h
| 32 | 50.21875 | 110 | 0.6739 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
3,885 |
pipewire.h
|
obsproject_obs-studio/plugins/linux-pipewire/pipewire.h
|
/* pipewire.h
*
* Copyright 2020 Georges Basile Stavracas Neto <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#pragma once
#include <obs-module.h>
#include <pipewire/pipewire.h>
typedef struct _obs_pipewire obs_pipewire;
typedef struct _obs_pipewire_stream obs_pipewire_stream;
struct obs_pipwire_connect_stream_info {
const char *stream_name;
struct pw_properties *stream_properties;
struct {
bool cursor_visible;
} screencast;
struct {
const struct spa_rectangle *resolution;
const struct spa_fraction *framerate;
} video;
};
obs_pipewire *obs_pipewire_connect_fd(int pipewire_fd, const struct pw_registry_events *registry_events,
void *user_data);
struct pw_registry *obs_pipewire_get_registry(obs_pipewire *obs_pw);
void obs_pipewire_roundtrip(obs_pipewire *obs_pw);
void obs_pipewire_destroy(obs_pipewire *obs_pw);
obs_pipewire_stream *obs_pipewire_connect_stream(obs_pipewire *obs_pw, obs_source_t *source, int pipewire_node,
const struct obs_pipwire_connect_stream_info *connect_info);
void obs_pipewire_stream_show(obs_pipewire_stream *obs_pw_stream);
void obs_pipewire_stream_hide(obs_pipewire_stream *obs_pw_stream);
uint32_t obs_pipewire_stream_get_width(obs_pipewire_stream *obs_pw_stream);
uint32_t obs_pipewire_stream_get_height(obs_pipewire_stream *obs_pw_stream);
void obs_pipewire_stream_video_render(obs_pipewire_stream *obs_pw_stream, gs_effect_t *effect);
void obs_pipewire_stream_set_cursor_visible(obs_pipewire_stream *obs_pw_stream, bool cursor_visible);
void obs_pipewire_stream_destroy(obs_pipewire_stream *obs_pw_stream);
void obs_pipewire_stream_set_framerate(obs_pipewire_stream *obs_pw_stream, const struct spa_fraction *framerate);
void obs_pipewire_stream_set_resolution(obs_pipewire_stream *obs_pw, const struct spa_rectangle *resolution);
| 2,497 |
C
|
.h
| 51 | 46.843137 | 113 | 0.78202 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
3,887 |
portal.h
|
obsproject_obs-studio/plugins/linux-pipewire/portal.h
|
/* portal.c
*
* Copyright 2021 Georges Basile Stavracas Neto <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#pragma once
#include <stdint.h>
#include <gio/gio.h>
typedef void (*portal_signal_callback)(GVariant *parameters, void *user_data);
GDBusConnection *portal_get_dbus_connection(void);
void portal_create_request_path(char **out_path, char **out_token);
void portal_create_session_path(char **out_path, char **out_token);
void portal_signal_subscribe(const char *path, GCancellable *cancellable, portal_signal_callback callback,
void *user_data);
| 1,253 |
C
|
.h
| 28 | 42.607143 | 106 | 0.763741 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
3,888 |
formats.h
|
obsproject_obs-studio/plugins/linux-pipewire/formats.h
|
/*
* formats.h
*
* Copyright 2023 Georges Basile Stavracas Neto <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#pragma once
#include <obs-module.h>
#include <spa/param/video/format-utils.h>
struct obs_pw_video_format {
uint32_t spa_format;
uint32_t drm_format;
enum gs_color_format gs_format;
enum video_format video_format;
bool swap_red_blue;
uint32_t bpp;
const char *pretty_name;
};
bool obs_pw_video_format_from_spa_format(uint32_t spa_format, struct obs_pw_video_format *out_format_info);
| 1,194 |
C
|
.h
| 33 | 34.242424 | 107 | 0.762976 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
3,889 |
camera-portal.h
|
obsproject_obs-studio/plugins/linux-pipewire/camera-portal.h
|
/* camera-portal.h
*
* Copyright 2021 Georges Basile Stavracas Neto <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#pragma once
void camera_portal_load(void);
void camera_portal_unload(void);
| 880 |
C
|
.h
| 22 | 38.090909 | 77 | 0.765187 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
3,925 |
audio-helpers.h
|
obsproject_obs-studio/plugins/win-capture/audio-helpers.h
|
#pragma once
#include "obs-module.h"
#include <util/windows/window-helpers.h>
#include "windows.h"
#define SETTING_CAPTURE_AUDIO "capture_audio"
#define TEXT_CAPTURE_AUDIO obs_module_text("CaptureAudio")
#define TEXT_CAPTURE_AUDIO_TT obs_module_text("CaptureAudio.TT")
#define TEXT_CAPTURE_AUDIO_SUFFIX obs_module_text("AudioSuffix")
#define AUDIO_SOURCE_TYPE "wasapi_process_output_capture"
void setup_audio_source(obs_source_t *parent, obs_source_t **child, const char *window, bool enabled,
enum window_priority priority);
void reconfigure_audio_source(obs_source_t *source, HWND window);
void rename_audio_source(void *param, calldata_t *data);
static bool audio_capture_available(void)
{
return obs_get_latest_input_type_id(AUDIO_SOURCE_TYPE) != NULL;
}
static void destroy_audio_source(obs_source_t *parent, obs_source_t **child)
{
setup_audio_source(parent, child, NULL, false, 0);
}
| 902 |
C
|
.h
| 21 | 41.428571 | 101 | 0.782857 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
3,934 |
compat-helpers.h
|
obsproject_obs-studio/plugins/win-capture/compat-helpers.h
|
#pragma once
enum source_type {
GAME_CAPTURE,
WINDOW_CAPTURE_BITBLT,
WINDOW_CAPTURE_WGC,
};
struct compat_result {
char *message;
enum obs_text_info_type severity;
};
extern struct compat_result *check_compatibility(const char *win_title, const char *win_class, const char *exe,
enum source_type type);
extern void compat_result_free(struct compat_result *res);
extern void compat_json_free();
| 409 |
C
|
.h
| 14 | 27.142857 | 111 | 0.772959 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
3,962 |
CMSampleBufferUtils.h
|
obsproject_obs-studio/plugins/mac-virtualcam/src/dal-plugin/CMSampleBufferUtils.h
|
//
// CMSampleBufferUtils.h
// dal-plugin
//
// Created by John Boiles on 5/8/20.
//
#include <CoreMediaIO/CMIOSampleBuffer.h>
CMSampleTimingInfo CMSampleTimingInfoForTimestamp(uint64_t timestampNanos, uint32_t fpsNumerator,
uint32_t fpsDenominator);
| 265 |
C
|
.h
| 9 | 27.333333 | 97 | 0.779528 |
obsproject/obs-studio
| 58,680 | 7,813 | 794 |
GPL-2.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
4,643 |
hogger.c
|
pbatard_rufus/res/hogger/hogger.c
|
/*
* Rufus: The Reliable USB Formatting Utility
* Commandline hogger, C version
* Copyright © 2014 Pete Batard <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <windows.h>
const char error_msg[] = "Unable to synchronize with UI application.";
int __cdecl main(int argc_ansi, char** argv_ansi)
{
DWORD size;
register HANDLE mutex, stdout;
stdout = GetStdHandle(STD_OUTPUT_HANDLE);
mutex = OpenMutexA(SYNCHRONIZE, FALSE, "Global/Rufus_CmdLine");
if (mutex == NULL)
goto error;
WaitForSingleObject(mutex, INFINITE);
goto out;
error:
WriteFile(stdout, error_msg, sizeof(error_msg), &size, 0);
out:
ExitProcess(0);
}
| 1,260 |
C
|
.c
| 35 | 34.057143 | 72 | 0.754918 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,653 |
format_fat32.c
|
pbatard_rufus/src/format_fat32.c
|
/*
* Rufus: The Reliable USB Formatting Utility
* Large FAT32 formatting
* Copyright © 2007-2009 Tom Thornhill/Ridgecrop
* Copyright © 2011-2024 Pete Batard <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include "rufus.h"
#include "file.h"
#include "drive.h"
#include "format.h"
#include "missing.h"
#include "resource.h"
#include "msapi_utf8.h"
#include "localization.h"
#define die(msg, err) do { uprintf(msg); ErrorStatus = RUFUS_ERROR(err); goto out; } while(0)
extern BOOL write_as_esp;
/* Large FAT32 */
#pragma pack(push, 1)
typedef struct tagFAT_BOOTSECTOR32
{
// Common fields.
BYTE sJmpBoot[3];
BYTE sOEMName[8];
WORD wBytsPerSec;
BYTE bSecPerClus;
WORD wRsvdSecCnt;
BYTE bNumFATs;
WORD wRootEntCnt;
WORD wTotSec16; // if zero, use dTotSec32 instead
BYTE bMedia;
WORD wFATSz16;
WORD wSecPerTrk;
WORD wNumHeads;
DWORD dHiddSec;
DWORD dTotSec32;
// Fat 32/16 only
DWORD dFATSz32;
WORD wExtFlags;
WORD wFSVer;
DWORD dRootClus;
WORD wFSInfo;
WORD wBkBootSec;
BYTE Reserved[12];
BYTE bDrvNum;
BYTE Reserved1;
BYTE bBootSig; // == 0x29 if next three fields are ok
DWORD dBS_VolID;
BYTE sVolLab[11];
BYTE sBS_FilSysType[8];
} FAT_BOOTSECTOR32;
typedef struct {
DWORD dLeadSig; // 0x41615252
BYTE sReserved1[480]; // zeros
DWORD dStrucSig; // 0x61417272
DWORD dFree_Count; // 0xFFFFFFFF
DWORD dNxt_Free; // 0xFFFFFFFF
BYTE sReserved2[12]; // zeros
DWORD dTrailSig; // 0xAA550000
} FAT_FSINFO;
#pragma pack(pop)
/*
* 28.2 CALCULATING THE VOLUME SERIAL NUMBER
*
* For example, say a disk was formatted on 26 Dec 95 at 9:55 PM and 41.94
* seconds. DOS takes the date and time just before it writes it to the
* disk.
*
* Low order word is calculated: Volume Serial Number is:
* Month & Day 12/26 0c1ah
* Sec & Hundredths 41:94 295eh 3578:1d02
* -----
* 3578h
*
* High order word is calculated:
* Hours & Minutes 21:55 1537h
* Year 1995 07cbh
* -----
* 1d02h
*/
static DWORD GetVolumeID(void)
{
SYSTEMTIME s;
DWORD d;
WORD lo, hi, tmp;
GetLocalTime(&s);
lo = s.wDay + (s.wMonth << 8);
tmp = (s.wMilliseconds / 10) + (s.wSecond << 8);
lo += tmp;
hi = s.wMinute + (s.wHour << 8);
hi += s.wYear;
d = lo + (hi << 16);
return d;
}
/*
* Proper computation of FAT size
* See: http://www.syslinux.org/archives/2016-February/024850.html
* and subsequent replies.
*/
static DWORD GetFATSizeSectors(DWORD DskSize, DWORD ReservedSecCnt, DWORD SecPerClus, DWORD NumFATs, DWORD BytesPerSect)
{
ULONGLONG Numerator, Denominator;
ULONGLONG FatElementSize = 4;
ULONGLONG ReservedClusCnt = 2;
ULONGLONG FatSz;
Numerator = DskSize - ReservedSecCnt + ReservedClusCnt * SecPerClus;
Denominator = (ULONGLONG)SecPerClus * BytesPerSect / FatElementSize + NumFATs;
FatSz = Numerator / Denominator + 1; // +1 to ensure we are rounded up
return (DWORD)FatSz;
}
/*
* Large FAT32 volume formatting from fat32format by Tom Thornhill
* http://www.ridgecrop.demon.co.uk/index.htm?fat32format.htm
*/
BOOL FormatLargeFAT32(DWORD DriveIndex, uint64_t PartitionOffset, DWORD ClusterSize, LPCSTR FSName, LPCSTR Label, DWORD Flags)
{
BOOL r = FALSE;
DWORD i;
HANDLE hLogicalVolume = NULL;
DWORD cbRet;
DISK_GEOMETRY dgDrive;
BYTE geometry_ex[256]; // DISK_GEOMETRY_EX is variable size
PDISK_GEOMETRY_EX xdgDrive = (PDISK_GEOMETRY_EX)(void*)geometry_ex;
PARTITION_INFORMATION piDrive;
PARTITION_INFORMATION_EX xpiDrive;
// Recommended values
DWORD ReservedSectCount = 32;
DWORD NumFATs = 2;
DWORD BackupBootSect = 6;
DWORD VolumeId = 0; // calculated before format
char* VolumeName = NULL;
DWORD BurstSize = 128; // Zero in blocks of 64K typically
// Calculated later
DWORD FatSize = 0;
DWORD BytesPerSect = 0;
DWORD SectorsPerCluster = 0;
DWORD TotalSectors = 0;
DWORD AlignSectors = 0;
DWORD SystemAreaSize = 0;
DWORD UserAreaSize = 0;
ULONGLONG qTotalSectors = 0;
// Structures to be written to the disk
FAT_BOOTSECTOR32* pFAT32BootSect = NULL;
FAT_FSINFO* pFAT32FsInfo = NULL;
DWORD* pFirstSectOfFat = NULL;
BYTE* pZeroSect = NULL;
char VolId[12] = "NO NAME ";
// Debug temp vars
ULONGLONG FatNeeded, ClusterCount;
if (safe_strncmp(FSName, "FAT", 3) != 0) {
ErrorStatus = RUFUS_ERROR(ERROR_INVALID_PARAMETER);
goto out;
}
PrintInfoDebug(0, MSG_222, "Large FAT32");
UpdateProgressWithInfoInit(NULL, TRUE);
VolumeId = GetVolumeID();
// Open the drive and lock it
hLogicalVolume = write_as_esp ?
AltGetLogicalHandle(DriveIndex, PartitionOffset, TRUE, TRUE, FALSE) :
GetLogicalHandle(DriveIndex, PartitionOffset, TRUE, TRUE, FALSE);
if (IS_ERROR(ErrorStatus))
goto out;
if ((hLogicalVolume == INVALID_HANDLE_VALUE) || (hLogicalVolume == NULL))
die("Invalid logical volume handle", ERROR_INVALID_HANDLE);
// Try to disappear the volume while we're formatting it
UnmountVolume(hLogicalVolume);
// Work out drive params
if (!DeviceIoControl (hLogicalVolume, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &dgDrive,
sizeof(dgDrive), &cbRet, NULL)) {
if (!DeviceIoControl (hLogicalVolume, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, NULL, 0, xdgDrive,
sizeof(geometry_ex), &cbRet, NULL)) {
uprintf("IOCTL_DISK_GET_DRIVE_GEOMETRY error: %s", WindowsErrorString());
die("Failed to get device geometry (both regular and _ex)", ERROR_NOT_SUPPORTED);
}
memcpy(&dgDrive, &xdgDrive->Geometry, sizeof(dgDrive));
}
if (dgDrive.BytesPerSector < 512)
dgDrive.BytesPerSector = 512;
if (IS_ERROR(ErrorStatus)) goto out;
if (!DeviceIoControl (hLogicalVolume, IOCTL_DISK_GET_PARTITION_INFO, NULL, 0, &piDrive,
sizeof(piDrive), &cbRet, NULL)) {
if (!DeviceIoControl (hLogicalVolume, IOCTL_DISK_GET_PARTITION_INFO_EX, NULL, 0, &xpiDrive,
sizeof(xpiDrive), &cbRet, NULL)) {
uprintf("IOCTL_DISK_GET_PARTITION_INFO error: %s", WindowsErrorString());
die("Failed to get partition info (both regular and _ex)", ERROR_NOT_SUPPORTED);
}
memset(&piDrive, 0, sizeof(piDrive));
piDrive.StartingOffset.QuadPart = xpiDrive.StartingOffset.QuadPart;
piDrive.PartitionLength.QuadPart = xpiDrive.PartitionLength.QuadPart;
piDrive.HiddenSectors = (DWORD)(xpiDrive.StartingOffset.QuadPart / dgDrive.BytesPerSector);
}
if (IS_ERROR(ErrorStatus)) goto out;
BytesPerSect = dgDrive.BytesPerSector;
// Checks on Disk Size
qTotalSectors = piDrive.PartitionLength.QuadPart / dgDrive.BytesPerSector;
// Low end limit - 65536 sectors
if (qTotalSectors < 65536) {
// Most FAT32 implementations would probably mount this volume just fine,
// but the spec says that we shouldn't do this, so we won't
die("This drive is too small for FAT32 - there must be at least 64K clusters", APPERR(ERROR_INVALID_CLUSTER_SIZE));
}
if (qTotalSectors >= 0xffffffff) {
// This is a more fundamental limitation on FAT32 - the total sector count in the root dir
// is 32bit. With a bit of creativity, FAT32 could be extended to handle at least 2^28 clusters
// There would need to be an extra field in the FSInfo sector, and the old sector count could
// be set to 0xffffffff. This is non standard though, the Windows FAT driver FASTFAT.SYS won't
// understand this. Perhaps a future version of FAT32 and FASTFAT will handle this.
die("This drive is too big for FAT32 - max 2TB supported", APPERR(ERROR_INVALID_VOLUME_SIZE));
}
// Set default cluster size
// https://support.microsoft.com/en-us/help/140365/default-cluster-size-for-ntfs-fat-and-exfat
if (ClusterSize == 0) {
if (piDrive.PartitionLength.QuadPart < 64 * MB)
ClusterSize = 512;
else if (piDrive.PartitionLength.QuadPart < 128 * MB)
ClusterSize = 1 * KB;
else if (piDrive.PartitionLength.QuadPart < 256 * MB)
ClusterSize = 2 * KB;
else if (piDrive.PartitionLength.QuadPart < 8 * GB)
ClusterSize = 4 * KB;
else if (piDrive.PartitionLength.QuadPart < 16 * GB)
ClusterSize = 8 * KB;
else if (piDrive.PartitionLength.QuadPart < 32 * GB)
ClusterSize = 16 * KB;
else if (piDrive.PartitionLength.QuadPart < 2 * TB)
ClusterSize = 32 * KB;
else
ClusterSize = 64 * KB;
}
// coverity[tainted_data]
pFAT32BootSect = (FAT_BOOTSECTOR32*)calloc(BytesPerSect, 1);
pFAT32FsInfo = (FAT_FSINFO*)calloc(BytesPerSect, 1);
pFirstSectOfFat = (DWORD*)calloc(BytesPerSect, 1);
if (!pFAT32BootSect || !pFAT32FsInfo || !pFirstSectOfFat) {
die("Failed to allocate memory", ERROR_NOT_ENOUGH_MEMORY);
}
// fill out the boot sector and fs info
pFAT32BootSect->sJmpBoot[0] = 0xEB;
pFAT32BootSect->sJmpBoot[1] = 0x58; // jmp.s $+0x5a is 0xeb 0x58, not 0xeb 0x5a. Thanks Marco!
pFAT32BootSect->sJmpBoot[2] = 0x90;
memcpy(pFAT32BootSect->sOEMName, "MSWIN4.1", 8);
pFAT32BootSect->wBytsPerSec = (WORD)BytesPerSect;
SectorsPerCluster = ClusterSize / BytesPerSect;
pFAT32BootSect->bSecPerClus = (BYTE)SectorsPerCluster;
pFAT32BootSect->bNumFATs = (BYTE)NumFATs;
pFAT32BootSect->wRootEntCnt = 0;
pFAT32BootSect->wTotSec16 = 0;
pFAT32BootSect->bMedia = 0xF8;
pFAT32BootSect->wFATSz16 = 0;
pFAT32BootSect->wSecPerTrk = (WORD)dgDrive.SectorsPerTrack;
pFAT32BootSect->wNumHeads = (WORD)dgDrive.TracksPerCylinder;
pFAT32BootSect->dHiddSec = (DWORD)piDrive.HiddenSectors;
TotalSectors = (DWORD)(piDrive.PartitionLength.QuadPart / dgDrive.BytesPerSector);
pFAT32BootSect->dTotSec32 = TotalSectors;
FatSize = GetFATSizeSectors(pFAT32BootSect->dTotSec32, pFAT32BootSect->wRsvdSecCnt,
pFAT32BootSect->bSecPerClus, pFAT32BootSect->bNumFATs, BytesPerSect);
// Update reserved sector count so that the start of data region is aligned to a MB boundary
SystemAreaSize = ReservedSectCount + NumFATs * FatSize;
AlignSectors = (1 * MB) / BytesPerSect;
SystemAreaSize = (SystemAreaSize + AlignSectors - 1) / AlignSectors * AlignSectors;
ReservedSectCount = SystemAreaSize - NumFATs * FatSize;
pFAT32BootSect->wRsvdSecCnt = (WORD)ReservedSectCount;
pFAT32BootSect->dFATSz32 = FatSize;
pFAT32BootSect->wExtFlags = 0;
pFAT32BootSect->wFSVer = 0;
pFAT32BootSect->dRootClus = 2;
pFAT32BootSect->wFSInfo = 1;
pFAT32BootSect->wBkBootSec = (WORD)BackupBootSect;
pFAT32BootSect->bDrvNum = 0x80;
pFAT32BootSect->Reserved1 = 0;
pFAT32BootSect->bBootSig = 0x29;
pFAT32BootSect->dBS_VolID = VolumeId;
memcpy(pFAT32BootSect->sVolLab, VolId, 11);
memcpy(pFAT32BootSect->sBS_FilSysType, "FAT32 ", 8);
((BYTE*)pFAT32BootSect)[510] = 0x55;
((BYTE*)pFAT32BootSect)[511] = 0xaa;
// FATGEN103.DOC says "NOTE: Many FAT documents mistakenly say that this 0xAA55 signature occupies the "last 2 bytes of
// the boot sector". This statement is correct if - and only if - BPB_BytsPerSec is 512. If BPB_BytsPerSec is greater than
// 512, the offsets of these signature bytes do not change (although it is perfectly OK for the last two bytes at the end
// of the boot sector to also contain this signature)."
//
// Windows seems to only check the bytes at offsets 510 and 511. Other OSs might check the ones at the end of the sector,
// so we'll put them there too.
if (BytesPerSect != 512) {
((BYTE*)pFAT32BootSect)[BytesPerSect - 2] = 0x55;
((BYTE*)pFAT32BootSect)[BytesPerSect - 1] = 0xaa;
}
// FSInfo sect
pFAT32FsInfo->dLeadSig = 0x41615252;
pFAT32FsInfo->dStrucSig = 0x61417272;
pFAT32FsInfo->dFree_Count = (DWORD)-1;
pFAT32FsInfo->dNxt_Free = (DWORD)-1;
pFAT32FsInfo->dTrailSig = 0xaa550000;
// First FAT Sector
pFirstSectOfFat[0] = 0x0ffffff8; // Reserved cluster 1 media id in low byte
pFirstSectOfFat[1] = 0x0fffffff; // Reserved cluster 2 EOC
pFirstSectOfFat[2] = 0x0fffffff; // end of cluster chain for root dir
// Write boot sector, fats
// Sector 0 Boot Sector
// Sector 1 FSInfo
// Sector 2 More boot code - we write zeros here
// Sector 3 unused
// Sector 4 unused
// Sector 5 unused
// Sector 6 Backup boot sector
// Sector 7 Backup FSInfo sector
// Sector 8 Backup 'more boot code'
// zeroed sectors up to ReservedSectCount
// FAT1 ReservedSectCount to ReservedSectCount + FatSize
// ...
// FATn ReservedSectCount to ReservedSectCount + FatSize
// RootDir - allocated to cluster2
UserAreaSize = TotalSectors - ReservedSectCount - (NumFATs * FatSize);
assert(SectorsPerCluster > 0);
ClusterCount = UserAreaSize / SectorsPerCluster;
// Sanity check for a cluster count of >2^28, since the upper 4 bits of the cluster values in
// the FAT are reserved.
if (ClusterCount > 0x0FFFFFFF) {
die("This drive has more than 2^28 clusters, try to specify a larger cluster size or use the default",
ERROR_INVALID_CLUSTER_SIZE);
}
// Sanity check - < 64K clusters means that the volume will be misdetected as FAT16
if (ClusterCount < 65536) {
die("FAT32 must have at least 65536 clusters, try to specify a smaller cluster size or use the default",
ERROR_INVALID_CLUSTER_SIZE);
}
// Sanity check, make sure the fat is big enough
// Convert the cluster count into a Fat sector count, and check the fat size value we calculated
// earlier is OK.
FatNeeded = ClusterCount * 4;
FatNeeded += (BytesPerSect - 1);
FatNeeded /= BytesPerSect;
if (FatNeeded > FatSize) {
die("This drive is too big for large FAT32 format", APPERR(ERROR_INVALID_VOLUME_SIZE));
}
// Now we're committed - print some info first
uprintf("Size : %s %lu sectors", SizeToHumanReadable(piDrive.PartitionLength.QuadPart, TRUE, FALSE), TotalSectors);
uprintf("Cluster size %lu bytes, %lu bytes per sector", SectorsPerCluster * BytesPerSect, BytesPerSect);
uprintf("Volume ID is %x:%x", VolumeId >> 16, VolumeId & 0xffff);
uprintf("%lu Reserved sectors, %lu sectors per FAT, %lu FATs", ReservedSectCount, FatSize, NumFATs);
uprintf("%llu Total clusters", ClusterCount);
// Fix up the FSInfo sector
pFAT32FsInfo->dFree_Count = (UserAreaSize / SectorsPerCluster) - 1;
pFAT32FsInfo->dNxt_Free = 3; // clusters 0-1 reserved, we used cluster 2 for the root dir
uprintf("%lu Free clusters", pFAT32FsInfo->dFree_Count);
// Work out the Cluster count
// First zero out ReservedSect + FatSize * NumFats + SectorsPerCluster
SystemAreaSize = ReservedSectCount + (NumFATs * FatSize) + SectorsPerCluster;
uprintf("Clearing out %d sectors for reserved sectors, FATs and root cluster...", SystemAreaSize);
// Not the most effective, but easy on RAM
pZeroSect = (BYTE*)calloc(BytesPerSect, BurstSize);
if (!pZeroSect) {
die("Failed to allocate memory", ERROR_NOT_ENOUGH_MEMORY);
}
for (i = 0; i < (SystemAreaSize + BurstSize - 1); i += BurstSize) {
UpdateProgressWithInfo(OP_FORMAT, MSG_217, (uint64_t)i, (uint64_t)SystemAreaSize + BurstSize);
CHECK_FOR_USER_CANCEL;
if (write_sectors(hLogicalVolume, BytesPerSect, i, BurstSize, pZeroSect) != (BytesPerSect * BurstSize)) {
die("Error clearing reserved sectors", ERROR_WRITE_FAULT);
}
}
uprintf ("Initializing reserved sectors and FATs...");
// Now we should write the boot sector and fsinfo twice, once at 0 and once at the backup boot sect position
for (i = 0; i < 2; i++) {
int SectorStart = (i == 0) ? 0 : BackupBootSect;
write_sectors(hLogicalVolume, BytesPerSect, SectorStart, 1, pFAT32BootSect);
write_sectors(hLogicalVolume, BytesPerSect, SectorStart + 1, 1, pFAT32FsInfo);
}
// Write the first fat sector in the right places
for (i = 0; i < NumFATs; i++) {
int SectorStart = ReservedSectCount + (i * FatSize);
uprintf("FAT #%d sector at address: %d", i, SectorStart);
write_sectors(hLogicalVolume, BytesPerSect, SectorStart, 1, pFirstSectOfFat);
}
if (!(Flags & FP_NO_BOOT)) {
// Must do it here, as have issues when trying to write the PBR after a remount
PrintInfoDebug(0, MSG_229);
if (!WritePBR(hLogicalVolume)) {
// Non fatal error, but the drive probably won't boot
uprintf("Could not write partition boot record - drive may not boot...");
}
}
// Set the FAT32 volume label
PrintInfo(0, MSG_221, lmprintf(MSG_307));
uprintf("Setting label...");
// Handle must be closed for SetVolumeLabel to work
safe_closehandle(hLogicalVolume);
VolumeName = write_as_esp ?
AltGetLogicalName(DriveIndex, PartitionOffset, TRUE, TRUE) :
GetLogicalName(DriveIndex, PartitionOffset, TRUE, TRUE);
if ((VolumeName == NULL) || (!SetVolumeLabelA(VolumeName, Label))) {
uprintf("Could not set label: %s", WindowsErrorString());
// Non fatal error
}
uprintf("Format completed.");
r = TRUE;
out:
safe_free(VolumeName);
safe_closehandle(hLogicalVolume);
safe_free(pFAT32BootSect);
safe_free(pFAT32FsInfo);
safe_free(pFirstSectOfFat);
safe_free(pZeroSect);
return r;
}
| 17,260 |
C
|
.c
| 426 | 38.246479 | 126 | 0.74167 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
4,654 |
badblocks.h
|
pbatard_rufus/src/badblocks.h
|
/*
* badblocks.c - Bad blocks checker
*
* Copyright (C) 1992, 1993, 1994 Remy Card <[email protected]>
* Laboratoire MASI, Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* Copyright 1995, 1996, 1997, 1998, 1999 by Theodore Ts'o
* Copyright 1999 by David Beattie
* Copyright 2011-2024 by Pete Batard
*
* This file is based on the minix file system programs fsck and mkfs
* written and copyrighted by Linus Torvalds <[email protected]>
*
* %Begin-Header%
* This file may be redistributed under the terms of the GNU Public
* License.
* %End-Header%
*/
#include <windows.h>
#include <stdint.h>
#include "ext2fs/ext2fs.h"
typedef struct bb_struct_u64_list *bb_badblocks_list;
typedef struct bb_struct_u64_iterate *bb_badblocks_iterate;
typedef struct bb_struct_u64_list *bb_u64_list;
typedef struct bb_struct_u64_iterate *bb_u64_iterate;
#define BB_ET_NO_MEMORY RUFUS_ERROR(ERROR_NOT_ENOUGH_MEMORY)
#define BB_ET_MAGIC_BADBLOCKS_LIST RUFUS_ERROR(ERROR_OBJECT_IN_LIST)
#define BB_ET_MAGIC_BADBLOCKS_ITERATE RUFUS_ERROR(ERROR_INVALID_BLOCK)
#define BB_CHECK_MAGIC(struct, code) if ((struct)->magic != (code)) return (code)
#define BB_BAD_BLOCKS_THRESHOLD 256
#define BB_BLOCKS_AT_ONCE 64
#define BB_SYS_PAGE_SIZE 4096
enum error_types { READ_ERROR, WRITE_ERROR, CORRUPTION_ERROR };
enum op_type { OP_READ, OP_WRITE };
/*
* Badblocks report
*/
typedef struct {
uint32_t bb_count;
uint32_t num_read_errors;
uint32_t num_write_errors;
uint32_t num_corruption_errors;
} badblocks_report;
/*
* Shared prototypes
*/
BOOL BadBlocks(HANDLE hPhysicalDrive, ULONGLONG disk_size, int nb_passes,
int flash_type, badblocks_report *report, FILE* fd);
| 1,869 |
C
|
.c
| 49 | 36.428571 | 86 | 0.692053 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
4,655 |
format_ext.c
|
pbatard_rufus/src/format_ext.c
|
/*
* Rufus: The Reliable USB Formatting Utility
* extfs formatting
* Copyright © 2019-2024 Pete Batard <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include "rufus.h"
#include "file.h"
#include "drive.h"
#include "format.h"
#include "missing.h"
#include "resource.h"
#include "msapi_utf8.h"
#include "localization.h"
#include "ext2fs/ext2fs.h"
extern const char* FileSystemLabel[FS_MAX];
extern io_manager nt_io_manager;
extern DWORD ext2_last_winerror(DWORD default_error);
static float ext2_percent_start = 0.0f, ext2_percent_share = 0.5f;
const float ext2_max_marker = 80.0f;
typedef struct {
uint64_t max_size;
uint32_t block_size;
uint32_t inode_size;
uint32_t inode_ratio;
} ext2fs_default_t;
const char* error_message(errcode_t error_code)
{
static char error_string[256];
switch (error_code) {
case EXT2_ET_MAGIC_EXT2FS_FILSYS:
case EXT2_ET_MAGIC_BADBLOCKS_LIST:
case EXT2_ET_MAGIC_BADBLOCKS_ITERATE:
case EXT2_ET_MAGIC_INODE_SCAN:
case EXT2_ET_MAGIC_IO_CHANNEL:
case EXT2_ET_MAGIC_IO_MANAGER:
case EXT2_ET_MAGIC_BLOCK_BITMAP:
case EXT2_ET_MAGIC_INODE_BITMAP:
case EXT2_ET_MAGIC_GENERIC_BITMAP:
case EXT2_ET_MAGIC_ICOUNT:
case EXT2_ET_MAGIC_EXTENT_HANDLE:
case EXT2_ET_BAD_MAGIC:
return "Bad magic";
case EXT2_ET_RO_FILSYS:
return "Read-only file system";
case EXT2_ET_GDESC_BAD_BLOCK_MAP:
case EXT2_ET_GDESC_BAD_INODE_MAP:
case EXT2_ET_GDESC_BAD_INODE_TABLE:
return "Bad map or table";
case EXT2_ET_UNEXPECTED_BLOCK_SIZE:
return "Unexpected block size";
case EXT2_ET_DIR_CORRUPTED:
return "Corrupted entry";
case EXT2_ET_GDESC_READ:
case EXT2_ET_GDESC_WRITE:
case EXT2_ET_INODE_BITMAP_WRITE:
case EXT2_ET_INODE_BITMAP_READ:
case EXT2_ET_BLOCK_BITMAP_WRITE:
case EXT2_ET_BLOCK_BITMAP_READ:
case EXT2_ET_INODE_TABLE_WRITE:
case EXT2_ET_INODE_TABLE_READ:
case EXT2_ET_NEXT_INODE_READ:
case EXT2_ET_SHORT_READ:
case EXT2_ET_SHORT_WRITE:
return "read/write error";
case EXT2_ET_DIR_NO_SPACE:
return "no space left";
case EXT2_ET_TOOSMALL:
return "Too small";
case EXT2_ET_BAD_DEVICE_NAME:
return "Bad device name";
case EXT2_ET_MISSING_INODE_TABLE:
return "Missing inode table";
case EXT2_ET_CORRUPT_SUPERBLOCK:
return "Superblock is corrupted";
case EXT2_ET_CALLBACK_NOTHANDLED:
return "Unhandled callback";
case EXT2_ET_BAD_BLOCK_IN_INODE_TABLE:
return "Bad block in inode table";
case EXT2_ET_UNSUPP_FEATURE:
case EXT2_ET_RO_UNSUPP_FEATURE:
case EXT2_ET_UNIMPLEMENTED:
return "Unsupported feature";
case EXT2_ET_LLSEEK_FAILED:
return "Seek failed";
case EXT2_ET_NO_MEMORY:
case EXT2_ET_BLOCK_ALLOC_FAIL:
case EXT2_ET_INODE_ALLOC_FAIL:
return "Out of memory";
case EXT2_ET_INVALID_ARGUMENT:
return "Invalid argument";
case EXT2_ET_NO_DIRECTORY:
return "No directory";
case EXT2_ET_FILE_NOT_FOUND:
return "File not found";
case EXT2_ET_FILE_RO:
return "File is read-only";
case EXT2_ET_DIR_EXISTS:
return "Directory already exists";
case EXT2_ET_CANCEL_REQUESTED:
return "Cancel requested";
case EXT2_ET_FILE_TOO_BIG:
return "File too big";
case EXT2_ET_JOURNAL_NOT_BLOCK:
case EXT2_ET_NO_JOURNAL_SB:
return "No journal superblock";
case EXT2_ET_JOURNAL_TOO_SMALL:
return "Journal too small";
case EXT2_ET_NO_JOURNAL:
return "No journal";
case EXT2_ET_TOO_MANY_INODES:
return "Too many inodes";
case EXT2_ET_NO_CURRENT_NODE:
return "No current node";
case EXT2_ET_OP_NOT_SUPPORTED:
return "Operation not supported";
case EXT2_ET_IO_CHANNEL_NO_SUPPORT_64:
return "I/O Channel does not support 64-bit operation";
case EXT2_ET_BAD_DESC_SIZE:
return "Bad descriptor size";
case EXT2_ET_INODE_CSUM_INVALID:
case EXT2_ET_INODE_BITMAP_CSUM_INVALID:
case EXT2_ET_EXTENT_CSUM_INVALID:
case EXT2_ET_DIR_CSUM_INVALID:
case EXT2_ET_EXT_ATTR_CSUM_INVALID:
case EXT2_ET_SB_CSUM_INVALID:
case EXT2_ET_BLOCK_BITMAP_CSUM_INVALID:
case EXT2_ET_MMP_CSUM_INVALID:
return "Invalid checksum";
case EXT2_ET_UNKNOWN_CSUM:
return "Unknown checksum";
case EXT2_ET_FILE_EXISTS:
return "File exists";
case EXT2_ET_INODE_IS_GARBAGE:
return "Inode is garbage";
case EXT2_ET_JOURNAL_FLAGS_WRONG:
return "Wrong journal flags";
case EXT2_ET_FILESYSTEM_CORRUPTED:
return "File system is corrupted";
case EXT2_ET_BAD_CRC:
return "Bad CRC";
case EXT2_ET_CORRUPT_JOURNAL_SB:
return "Journal Superblock is corrupted";
case EXT2_ET_INODE_CORRUPTED:
case EXT2_ET_EA_INODE_CORRUPTED:
return "Inode is corrupted";
case EXT2_ET_NO_GDESC:
return "Group descriptors not loaded";
default:
if ((error_code > EXT2_ET_BASE) && error_code < (EXT2_ET_BASE + 1000)) {
static_sprintf(error_string, "Unknown ext2fs error %ld (EXT2_ET_BASE + %ld)", error_code, error_code - EXT2_ET_BASE);
} else {
SetLastError((ErrorStatus == 0) ? RUFUS_ERROR(error_code & 0xFFFF) : ErrorStatus);
static_sprintf(error_string, "%s", WindowsErrorString());
}
return error_string;
}
}
errcode_t ext2fs_print_progress(int64_t cur_value, int64_t max_value)
{
static int64_t last_value = -1;
if (max_value == 0)
return 0;
UpdateProgressWithInfo(OP_FORMAT, MSG_217, (uint64_t)((ext2_percent_start * max_value) + (ext2_percent_share * cur_value)), max_value);
cur_value = (int64_t)(((float)cur_value / (float)max_value) * min(ext2_max_marker, (float)max_value));
if (cur_value != last_value) {
last_value = cur_value;
uprintfs("+");
}
return IS_ERROR(ErrorStatus) ? EXT2_ET_CANCEL_REQUESTED : 0;
}
const char* GetExtFsLabel(DWORD DriveIndex, uint64_t PartitionOffset)
{
static char label[EXT2_LABEL_LEN + 1];
errcode_t r;
ext2_filsys ext2fs = NULL;
io_manager manager = nt_io_manager;
char* volume_name = GetExtPartitionName(DriveIndex, PartitionOffset);
if (volume_name == NULL)
return NULL;
r = ext2fs_open(volume_name, EXT2_FLAG_SKIP_MMP, 0, 0, manager, &ext2fs);
free(volume_name);
if (r == 0) {
assert(ext2fs != NULL);
strncpy(label, ext2fs->super->s_volume_name, EXT2_LABEL_LEN);
label[EXT2_LABEL_LEN] = 0;
}
if (ext2fs != NULL)
ext2fs_close(ext2fs);
return (r == 0) ? label : NULL;
}
#define TEST_IMG_PATH "\\??\\C:\\tmp\\disk.img"
#define TEST_IMG_SIZE 4000 // Size in MB
#define SET_EXT2_FORMAT_ERROR(x) if (!IS_ERROR(ErrorStatus)) ErrorStatus = ext2_last_winerror(x)
BOOL FormatExtFs(DWORD DriveIndex, uint64_t PartitionOffset, DWORD BlockSize, LPCSTR FSName, LPCSTR Label, DWORD Flags)
{
// Mostly taken from mke2fs.conf
const float reserve_ratio = 0.05f;
const ext2fs_default_t ext2fs_default[5] = {
{ 3 * MB, 1024, 128, 3}, // "floppy"
{ 512 * MB, 1024, 128, 2}, // "small"
{ 4 * GB, 4096, 256, 2}, // "default"
{ 16 * GB, 4096, 256, 3}, // "big"
{ 1024 * TB, 4096, 256, 4} // "huge"
};
BOOL ret = FALSE;
char* volume_name = NULL;
int i, count;
struct ext2_super_block features = { 0 };
io_manager manager = nt_io_manager;
blk_t journal_size;
blk64_t size = 0, cur;
ext2_filsys ext2fs = NULL;
errcode_t r;
uint8_t* buf = NULL;
#if defined(RUFUS_TEST)
// Create a disk image file to test
uint8_t zb[1024];
HANDLE h;
DWORD dwSize;
HCRYPTPROV hCryptProv = 0;
volume_name = strdup(TEST_IMG_PATH);
uprintf("Creating '%s'...", volume_name);
if (!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) || !CryptGenRandom(hCryptProv, sizeof(zb), zb)) {
uprintf("Failed to randomize buffer - filling with constant value");
memset(zb, rand(), sizeof(zb));
}
CryptReleaseContext(hCryptProv, 0);
h = CreateFileU(volume_name, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
for (i = 0; i < TEST_IMG_SIZE * sizeof(zb); i++) {
if (!WriteFile(h, zb, sizeof(zb), &dwSize, NULL) || (dwSize != sizeof(zb))) {
uprintf("Write error: %s", WindowsErrorString());
break;
}
}
CloseHandle(h);
#else
volume_name = GetExtPartitionName(DriveIndex, PartitionOffset);
#endif
if ((volume_name == NULL) | (strlen(FSName) != 4) || (strncmp(FSName, "ext", 3) != 0)) {
ErrorStatus = RUFUS_ERROR(ERROR_INVALID_PARAMETER);
goto out;
}
if (strchr(volume_name, ' ') != NULL)
uprintf("Notice: Using physical device to access partition data");
if ((strcmp(FSName, FileSystemLabel[FS_EXT2]) != 0) && (strcmp(FSName, FileSystemLabel[FS_EXT3]) != 0)) {
if (strcmp(FSName, FileSystemLabel[FS_EXT4]) == 0)
uprintf("ext4 file system is not supported, defaulting to ext3");
else
uprintf("Invalid ext file system version requested, defaulting to ext3");
FSName = FileSystemLabel[FS_EXT3];
}
PrintInfoDebug(0, MSG_222, FSName);
UpdateProgressWithInfoInit(NULL, TRUE);
// Figure out the volume size and block size
r = ext2fs_get_device_size2(volume_name, KB, &size);
if ((r != 0) || (size == 0)) {
SET_EXT2_FORMAT_ERROR(ERROR_READ_FAULT);
uprintf("Could not read device size: %s", error_message(r));
goto out;
}
size *= KB;
for (i = 0; i < ARRAYSIZE(ext2fs_default); i++) {
if (size < ext2fs_default[i].max_size)
break;
}
assert(i < ARRAYSIZE(ext2fs_default));
if ((BlockSize == 0) || (BlockSize < EXT2_MIN_BLOCK_SIZE))
BlockSize = ext2fs_default[i].block_size;
assert(IS_POWER_OF_2(BlockSize));
for (features.s_log_block_size = 0; EXT2_BLOCK_SIZE_BITS(&features) <= EXT2_MAX_BLOCK_LOG_SIZE; features.s_log_block_size++) {
if (EXT2_BLOCK_SIZE(&features) == BlockSize)
break;
}
assert(EXT2_BLOCK_SIZE_BITS(&features) <= EXT2_MAX_BLOCK_LOG_SIZE);
features.s_log_cluster_size = features.s_log_block_size;
size /= BlockSize;
// ext2 and ext3 have a can only accommodate up to Blocksize * 2^32 sized volumes
if (((strcmp(FSName, FileSystemLabel[FS_EXT2]) == 0) || (strcmp(FSName, FileSystemLabel[FS_EXT3]) == 0)) &&
(size >= 0x100000000ULL)) {
SET_EXT2_FORMAT_ERROR(ERROR_INVALID_VOLUME_SIZE);
uprintf("Volume size is too large for ext2 or ext3");
goto out;
}
// Set the blocks, reserved blocks and inodes
ext2fs_blocks_count_set(&features, size);
ext2fs_r_blocks_count_set(&features, (blk64_t)(reserve_ratio * size));
features.s_rev_level = 1;
features.s_inode_size = ext2fs_default[i].inode_size;
features.s_inodes_count = ((ext2fs_blocks_count(&features) >> ext2fs_default[i].inode_ratio) > UINT32_MAX) ?
UINT32_MAX : (uint32_t)(ext2fs_blocks_count(&features) >> ext2fs_default[i].inode_ratio);
uprintf("%d possible inodes out of %lld blocks (block size = %d)", features.s_inodes_count, size, EXT2_BLOCK_SIZE(&features));
uprintf("%lld blocks (%0.1f%%) reserved for the super user", ext2fs_r_blocks_count(&features), reserve_ratio * 100.0f);
// Set features
ext2fs_set_feature_dir_index(&features);
ext2fs_set_feature_filetype(&features);
ext2fs_set_feature_large_file(&features);
ext2fs_set_feature_sparse_super(&features);
ext2fs_set_feature_xattr(&features);
if (FSName[3] != '2')
ext2fs_set_feature_journal(&features);
features.s_default_mount_opts = EXT2_DEFM_XATTR_USER | EXT2_DEFM_ACL;
// Now that we have set our base features, initialize a virtual superblock
r = ext2fs_initialize(volume_name, EXT2_FLAG_EXCLUSIVE | EXT2_FLAG_64BITS, &features, manager, &ext2fs);
if (r != 0) {
SET_EXT2_FORMAT_ERROR(ERROR_INVALID_DATA);
uprintf("Could not initialize %s features: %s", FSName, error_message(r));
goto out;
}
// Zero 16 blocks of data from the start of our volume
buf = calloc(16, ext2fs->io->block_size);
assert(buf != NULL);
r = io_channel_write_blk64(ext2fs->io, 0, 16, buf);
safe_free(buf);
if (r != 0) {
SET_EXT2_FORMAT_ERROR(ERROR_WRITE_FAULT);
uprintf("Could not zero %s superblock area: %s", FSName, error_message(r));
goto out;
}
// Finish setting up the file system
IGNORE_RETVAL(CoCreateGuid((GUID*)ext2fs->super->s_uuid));
ext2fs_init_csum_seed(ext2fs);
ext2fs->super->s_def_hash_version = EXT2_HASH_HALF_MD4;
IGNORE_RETVAL(CoCreateGuid((GUID*)ext2fs->super->s_hash_seed));
ext2fs->super->s_max_mnt_count = -1;
ext2fs->super->s_creator_os = EXT2_OS_WINDOWS;
ext2fs->super->s_errors = EXT2_ERRORS_CONTINUE;
if (Label != NULL)
static_strcpy(ext2fs->super->s_volume_name, Label);
r = ext2fs_allocate_tables(ext2fs);
if (r != 0) {
SET_EXT2_FORMAT_ERROR(ERROR_INVALID_DATA);
uprintf("Could not allocate %s tables: %s", FSName, error_message(r));
goto out;
}
r = ext2fs_convert_subcluster_bitmap(ext2fs, &ext2fs->block_map);
if (r != 0) {
uprintf("Could not set %s cluster bitmap: %s", FSName, error_message(r));
goto out;
}
ext2_percent_start = 0.0f;
ext2_percent_share = (FSName[3] == '2') ? 1.0f : 0.5f;
uprintf("Creating %d inode sets: [1 marker = %0.1f set(s)]", ext2fs->group_desc_count,
max((float)ext2fs->group_desc_count / ext2_max_marker, 1.0f));
for (i = 0; i < (int)ext2fs->group_desc_count; i++) {
if (ext2fs_print_progress((int64_t)i, (int64_t)ext2fs->group_desc_count))
goto out;
cur = ext2fs_inode_table_loc(ext2fs, i);
count = ext2fs_div_ceil((ext2fs->super->s_inodes_per_group - ext2fs_bg_itable_unused(ext2fs, i))
* EXT2_INODE_SIZE(ext2fs->super), EXT2_BLOCK_SIZE(ext2fs->super));
r = ext2fs_zero_blocks2(ext2fs, cur, count, &cur, &count);
if (r != 0) {
SET_EXT2_FORMAT_ERROR(ERROR_WRITE_FAULT);
uprintf("\r\nCould not zero inode set at position %llu (%d blocks): %s", cur, count, error_message(r));
goto out;
}
}
uprintfs("\r\n");
// Create root and lost+found dirs
r = ext2fs_mkdir(ext2fs, EXT2_ROOT_INO, EXT2_ROOT_INO, 0);
if (r != 0) {
SET_EXT2_FORMAT_ERROR(ERROR_FILE_CORRUPT);
uprintf("Failed to create %s root dir: %s", FSName, error_message(r));
goto out;
}
ext2fs->umask = 077;
r = ext2fs_mkdir(ext2fs, EXT2_ROOT_INO, 0, "lost+found");
if (r != 0) {
SET_EXT2_FORMAT_ERROR(ERROR_FILE_CORRUPT);
uprintf("Failed to create %s 'lost+found' dir: %s", FSName, error_message(r));
goto out;
}
// Create bitmaps
for (i = EXT2_ROOT_INO + 1; i < (int)EXT2_FIRST_INODE(ext2fs->super); i++)
ext2fs_inode_alloc_stats(ext2fs, i, 1);
ext2fs_mark_ib_dirty(ext2fs);
r = ext2fs_mark_inode_bitmap2(ext2fs->inode_map, EXT2_BAD_INO);
if (r != 0) {
SET_EXT2_FORMAT_ERROR(ERROR_WRITE_FAULT);
uprintf("Could not set inode bitmaps: %s", error_message(r));
goto out;
}
ext2fs_inode_alloc_stats(ext2fs, EXT2_BAD_INO, 1);
r = ext2fs_update_bb_inode(ext2fs, NULL);
if (r != 0) {
SET_EXT2_FORMAT_ERROR(ERROR_WRITE_FAULT);
uprintf("Could not set inode stats: %s", error_message(r));
goto out;
}
if (FSName[3] != '2') {
// Create the journal
ext2_percent_start = 0.5f;
journal_size = ext2fs_default_journal_size(ext2fs_blocks_count(ext2fs->super));
journal_size /= 2; // That journal init is really killing us!
uprintf("Creating %d journal blocks: [1 marker = %0.1f block(s)]", journal_size,
max((float)journal_size / ext2_max_marker, 1.0f));
// Even with EXT2_MKJOURNAL_LAZYINIT, this call is absolutely dreadful in terms of speed...
r = ext2fs_add_journal_inode(ext2fs, journal_size, EXT2_MKJOURNAL_NO_MNT_CHECK | ((Flags & FP_QUICK) ? EXT2_MKJOURNAL_LAZYINIT : 0));
uprintfs("\r\n");
if (r != 0) {
SET_EXT2_FORMAT_ERROR(ERROR_WRITE_FAULT);
uprintf("Could not create %s journal: %s", FSName, error_message(r));
goto out;
}
}
// Create a 'persistence.conf' file if required
if (Flags & FP_CREATE_PERSISTENCE_CONF) {
// You *do* want the LF at the end of the "/ union" line, else Debian Live bails out...
const char* name = "persistence.conf", data[] = "/ union\n";
int written = 0, fsize = sizeof(data) - 1;
ext2_file_t ext2fd;
ext2_ino_t inode_id;
time_t ctime = time(NULL);
struct ext2_inode inode = { 0 };
// Don't care about the Y2K38 problem of ext2/ext3 for a 'persistence.conf' timestamp
if (ctime > UINT32_MAX)
ctime = UINT32_MAX;
inode.i_mode = 0100644;
inode.i_links_count = 1;
// coverity[store_truncates_time_t]
inode.i_atime = (uint32_t)ctime;
// coverity[store_truncates_time_t]
inode.i_ctime = (uint32_t)ctime;
// coverity[store_truncates_time_t]
inode.i_mtime = (uint32_t)ctime;
inode.i_size = fsize;
ext2fs_namei(ext2fs, EXT2_ROOT_INO, EXT2_ROOT_INO, name, &inode_id);
ext2fs_new_inode(ext2fs, EXT2_ROOT_INO, 010755, 0, &inode_id);
ext2fs_link(ext2fs, EXT2_ROOT_INO, name, inode_id, EXT2_FT_REG_FILE);
ext2fs_inode_alloc_stats(ext2fs, inode_id, 1);
ext2fs_write_new_inode(ext2fs, inode_id, &inode);
ext2fs_file_open(ext2fs, inode_id, EXT2_FILE_WRITE, &ext2fd);
if ((ext2fs_file_write(ext2fd, data, fsize, &written) != 0) || (written != fsize))
uprintf("Error: Could not create '%s' file", name);
else
uprintf("Created '%s' file", name);
ext2fs_file_close(ext2fd);
}
// Finally we can call close() to get the file system gets created
r = ext2fs_close(ext2fs);
if (r == 0) {
// Make sure ext2fs isn't freed twice
ext2fs = NULL;
} else {
SET_EXT2_FORMAT_ERROR(ERROR_WRITE_FAULT);
uprintf("Could not create %s volume: %s", FSName, error_message(r));
goto out;
}
UpdateProgressWithInfo(OP_FORMAT, MSG_217, 100, 100);
ret = TRUE;
out:
free(volume_name);
ext2fs_free(ext2fs);
free(buf);
return ret;
}
| 17,742 |
C
|
.c
| 477 | 34.809224 | 136 | 0.711873 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
4,657 |
localization_data.h
|
pbatard_rufus/src/localization_data.h
|
/*
* Rufus: The Reliable USB Formatting Utility
* Localization tables - autogenerated from resource.h
* Copyright © 2013-2024 Pete Batard <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <windows.h>
#include "resource.h"
#include "localization.h"
#define LOC_CTRL(x) { #x, x }
#define LOC_DLG(x) { x, NULL, {NULL, NULL} }
// Control IDs
const loc_control_id control_id[] = {
// The dialog IDs must come first
LOC_CTRL(IDD_DIALOG),
LOC_CTRL(IDD_ABOUTBOX),
LOC_CTRL(IDD_NOTIFICATION),
LOC_CTRL(IDD_SELECTION),
LOC_CTRL(IDD_LICENSE),
LOC_CTRL(IDD_LOG),
LOC_CTRL(IDD_UPDATE_POLICY),
LOC_CTRL(IDD_NEW_VERSION),
LOC_CTRL(IDD_HASH),
LOC_CTRL(IDD_LIST),
LOC_CTRL(IDC_DEVICE),
LOC_CTRL(IDC_FILE_SYSTEM),
LOC_CTRL(IDC_START),
LOC_CTRL(IDC_PARTITION_TYPE),
LOC_CTRL(IDC_CLUSTER_SIZE),
LOC_CTRL(IDC_STATUS),
LOC_CTRL(IDC_LABEL),
LOC_CTRL(IDC_QUICK_FORMAT),
LOC_CTRL(IDC_BAD_BLOCKS),
LOC_CTRL(IDC_PROGRESS),
LOC_CTRL(IDC_BOOT_SELECTION),
LOC_CTRL(IDC_NB_PASSES),
LOC_CTRL(IDC_TEST),
LOC_CTRL(IDC_SELECT),
LOC_CTRL(IDC_EXTENDED_LABEL),
LOC_CTRL(IDC_UEFI_MEDIA_VALIDATION),
LOC_CTRL(IDC_TARGET_SYSTEM),
LOC_CTRL(IDC_PERSISTENCE_SIZE),
LOC_CTRL(IDC_PERSISTENCE_UNITS),
LOC_CTRL(IDC_OLD_BIOS_FIXES),
LOC_CTRL(IDC_LIST_USB_HDD),
LOC_CTRL(IDC_STATUS_TOOLBAR),
LOC_CTRL(IDC_SAVE),
LOC_CTRL(IDC_HASH),
LOC_CTRL(IDC_IMAGE_OPTION),
LOC_CTRL(IDC_PERSISTENCE_SLIDER),
LOC_CTRL(IDC_ADVANCED_DRIVE_PROPERTIES),
LOC_CTRL(IDC_ADVANCED_FORMAT_OPTIONS),
LOC_CTRL(IDC_ABOUT_LICENSE),
LOC_CTRL(IDC_ABOUT_ICON),
LOC_CTRL(IDC_ABOUT_COPYRIGHTS),
LOC_CTRL(IDC_ABOUT_BLURB),
LOC_CTRL(IDC_LICENSE_TEXT),
LOC_CTRL(IDC_NOTIFICATION_ICON),
LOC_CTRL(IDC_NOTIFICATION_TEXT),
LOC_CTRL(IDC_NOTIFICATION_LINE),
LOC_CTRL(IDC_ADVANCED_DEVICE_TOOLBAR),
LOC_CTRL(IDC_ADVANCED_FORMAT_TOOLBAR),
LOC_CTRL(IDC_SAVE_TOOLBAR),
LOC_CTRL(IDC_HASH_TOOLBAR),
LOC_CTRL(IDC_MULTI_TOOLBAR),
LOC_CTRL(IDC_LANG),
LOC_CTRL(IDC_ABOUT),
LOC_CTRL(IDC_SETTINGS),
LOC_CTRL(IDC_LOG),
LOC_CTRL(IDC_LOG_EDIT),
LOC_CTRL(IDC_LOG_SAVE),
LOC_CTRL(IDC_LOG_CLEAR),
LOC_CTRL(IDC_DONT_DISPLAY_AGAIN),
LOC_CTRL(IDC_MORE_INFO),
LOC_CTRL(IDC_POLICY),
LOC_CTRL(IDC_UPDATE_FREQUENCY),
LOC_CTRL(IDC_INCLUDE_BETAS),
LOC_CTRL(IDC_RELEASE_NOTES),
LOC_CTRL(IDC_DOWNLOAD),
LOC_CTRL(IDC_CHECK_NOW),
LOC_CTRL(IDC_WEBSITE),
LOC_CTRL(IDC_YOUR_VERSION),
LOC_CTRL(IDC_LATEST_VERSION),
LOC_CTRL(IDC_DOWNLOAD_URL),
LOC_CTRL(IDC_MD5),
LOC_CTRL(IDC_SHA1),
LOC_CTRL(IDC_SHA256),
LOC_CTRL(IDC_SHA512),
LOC_CTRL(IDC_SELECTION_ICON),
LOC_CTRL(IDC_SELECTION_TEXT),
LOC_CTRL(IDC_SELECTION_LINE),
LOC_CTRL(IDC_SELECTION_CHOICE1),
LOC_CTRL(IDC_SELECTION_CHOICE2),
LOC_CTRL(IDC_SELECTION_CHOICE3),
LOC_CTRL(IDC_SELECTION_CHOICE4),
LOC_CTRL(IDC_SELECTION_CHOICE5),
LOC_CTRL(IDC_SELECTION_CHOICE6),
LOC_CTRL(IDC_SELECTION_CHOICE7),
LOC_CTRL(IDC_SELECTION_CHOICE8),
LOC_CTRL(IDC_SELECTION_CHOICE9),
LOC_CTRL(IDC_SELECTION_CHOICE10),
LOC_CTRL(IDC_SELECTION_CHOICE11),
LOC_CTRL(IDC_SELECTION_CHOICE12),
LOC_CTRL(IDC_SELECTION_CHOICE13),
LOC_CTRL(IDC_SELECTION_CHOICE14),
LOC_CTRL(IDC_SELECTION_CHOICE15),
LOC_CTRL(IDC_SELECTION_CHOICEMAX),
LOC_CTRL(IDC_LIST_ICON),
LOC_CTRL(IDC_LIST_TEXT),
LOC_CTRL(IDC_LIST_LINE),
LOC_CTRL(IDC_LIST_ITEM1),
LOC_CTRL(IDC_LIST_ITEM2),
LOC_CTRL(IDC_LIST_ITEM3),
LOC_CTRL(IDC_LIST_ITEM4),
LOC_CTRL(IDC_LIST_ITEM5),
LOC_CTRL(IDC_LIST_ITEM6),
LOC_CTRL(IDC_LIST_ITEM7),
LOC_CTRL(IDC_LIST_ITEM8),
LOC_CTRL(IDC_LIST_ITEM9),
LOC_CTRL(IDC_LIST_ITEM10),
LOC_CTRL(IDC_LIST_ITEM11),
LOC_CTRL(IDC_LIST_ITEM12),
LOC_CTRL(IDC_LIST_ITEM13),
LOC_CTRL(IDC_LIST_ITEM14),
LOC_CTRL(IDC_LIST_ITEM15),
LOC_CTRL(IDC_LIST_ITEMMAX),
LOC_CTRL(IDS_DEVICE_TXT),
LOC_CTRL(IDS_PARTITION_TYPE_TXT),
LOC_CTRL(IDS_FILE_SYSTEM_TXT),
LOC_CTRL(IDS_CLUSTER_SIZE_TXT),
LOC_CTRL(IDS_LABEL_TXT),
LOC_CTRL(IDS_CSM_HELP_TXT),
LOC_CTRL(IDS_UPDATE_SETTINGS_GRP),
LOC_CTRL(IDS_UPDATE_FREQUENCY_TXT),
LOC_CTRL(IDS_INCLUDE_BETAS_TXT),
LOC_CTRL(IDS_NEW_VERSION_AVAIL_TXT),
LOC_CTRL(IDS_NEW_VERSION_DOWNLOAD_GRP),
LOC_CTRL(IDS_NEW_VERSION_NOTES_GRP),
LOC_CTRL(IDS_CHECK_NOW_GRP),
LOC_CTRL(IDS_TARGET_SYSTEM_TXT),
LOC_CTRL(IDS_IMAGE_OPTION_TXT),
LOC_CTRL(IDS_BOOT_SELECTION_TXT),
LOC_CTRL(IDS_DRIVE_PROPERTIES_TXT),
LOC_CTRL(IDS_FORMAT_OPTIONS_TXT),
LOC_CTRL(IDS_STATUS_TXT),
LOC_CTRL(MSG_000),
LOC_CTRL(MSG_001),
LOC_CTRL(MSG_002),
LOC_CTRL(MSG_003),
LOC_CTRL(MSG_004),
LOC_CTRL(MSG_005),
LOC_CTRL(MSG_006),
LOC_CTRL(MSG_007),
LOC_CTRL(MSG_008),
LOC_CTRL(MSG_009),
LOC_CTRL(MSG_010),
LOC_CTRL(MSG_011),
LOC_CTRL(MSG_012),
LOC_CTRL(MSG_013),
LOC_CTRL(MSG_014),
LOC_CTRL(MSG_015),
LOC_CTRL(MSG_016),
LOC_CTRL(MSG_017),
LOC_CTRL(MSG_018),
LOC_CTRL(MSG_019),
LOC_CTRL(MSG_020),
LOC_CTRL(MSG_021),
LOC_CTRL(MSG_022),
LOC_CTRL(MSG_023),
LOC_CTRL(MSG_024),
LOC_CTRL(MSG_025),
LOC_CTRL(MSG_026),
LOC_CTRL(MSG_027),
LOC_CTRL(MSG_028),
LOC_CTRL(MSG_029),
LOC_CTRL(MSG_030),
LOC_CTRL(MSG_031),
LOC_CTRL(MSG_032),
LOC_CTRL(MSG_033),
LOC_CTRL(MSG_034),
LOC_CTRL(MSG_035),
LOC_CTRL(MSG_036),
LOC_CTRL(MSG_037),
LOC_CTRL(MSG_038),
LOC_CTRL(MSG_039),
LOC_CTRL(MSG_040),
LOC_CTRL(MSG_041),
LOC_CTRL(MSG_042),
LOC_CTRL(MSG_043),
LOC_CTRL(MSG_044),
LOC_CTRL(MSG_045),
LOC_CTRL(MSG_046),
LOC_CTRL(MSG_047),
LOC_CTRL(MSG_048),
LOC_CTRL(MSG_049),
LOC_CTRL(MSG_050),
LOC_CTRL(MSG_051),
LOC_CTRL(MSG_052),
LOC_CTRL(MSG_053),
LOC_CTRL(MSG_054),
LOC_CTRL(MSG_055),
LOC_CTRL(MSG_056),
LOC_CTRL(MSG_057),
LOC_CTRL(MSG_058),
LOC_CTRL(MSG_059),
LOC_CTRL(MSG_060),
LOC_CTRL(MSG_061),
LOC_CTRL(MSG_062),
LOC_CTRL(MSG_063),
LOC_CTRL(MSG_064),
LOC_CTRL(MSG_065),
LOC_CTRL(MSG_066),
LOC_CTRL(MSG_067),
LOC_CTRL(MSG_068),
LOC_CTRL(MSG_069),
LOC_CTRL(MSG_070),
LOC_CTRL(MSG_071),
LOC_CTRL(MSG_072),
LOC_CTRL(MSG_073),
LOC_CTRL(MSG_074),
LOC_CTRL(MSG_075),
LOC_CTRL(MSG_076),
LOC_CTRL(MSG_077),
LOC_CTRL(MSG_078),
LOC_CTRL(MSG_079),
LOC_CTRL(MSG_080),
LOC_CTRL(MSG_081),
LOC_CTRL(MSG_082),
LOC_CTRL(MSG_083),
LOC_CTRL(MSG_084),
LOC_CTRL(MSG_085),
LOC_CTRL(MSG_086),
LOC_CTRL(MSG_087),
LOC_CTRL(MSG_088),
LOC_CTRL(MSG_089),
LOC_CTRL(MSG_090),
LOC_CTRL(MSG_091),
LOC_CTRL(MSG_092),
LOC_CTRL(MSG_093),
LOC_CTRL(MSG_094),
LOC_CTRL(MSG_095),
LOC_CTRL(MSG_096),
LOC_CTRL(MSG_097),
LOC_CTRL(MSG_098),
LOC_CTRL(MSG_099),
LOC_CTRL(MSG_100),
LOC_CTRL(MSG_101),
LOC_CTRL(MSG_102),
LOC_CTRL(MSG_103),
LOC_CTRL(MSG_104),
LOC_CTRL(MSG_105),
LOC_CTRL(MSG_106),
LOC_CTRL(MSG_107),
LOC_CTRL(MSG_108),
LOC_CTRL(MSG_109),
LOC_CTRL(MSG_110),
LOC_CTRL(MSG_111),
LOC_CTRL(MSG_112),
LOC_CTRL(MSG_113),
LOC_CTRL(MSG_114),
LOC_CTRL(MSG_115),
LOC_CTRL(MSG_116),
LOC_CTRL(MSG_117),
LOC_CTRL(MSG_118),
LOC_CTRL(MSG_119),
LOC_CTRL(MSG_120),
LOC_CTRL(MSG_121),
LOC_CTRL(MSG_122),
LOC_CTRL(MSG_123),
LOC_CTRL(MSG_124),
LOC_CTRL(MSG_125),
LOC_CTRL(MSG_126),
LOC_CTRL(MSG_127),
LOC_CTRL(MSG_128),
LOC_CTRL(MSG_129),
LOC_CTRL(MSG_130),
LOC_CTRL(MSG_131),
LOC_CTRL(MSG_132),
LOC_CTRL(MSG_133),
LOC_CTRL(MSG_134),
LOC_CTRL(MSG_135),
LOC_CTRL(MSG_136),
LOC_CTRL(MSG_137),
LOC_CTRL(MSG_138),
LOC_CTRL(MSG_139),
LOC_CTRL(MSG_140),
LOC_CTRL(MSG_141),
LOC_CTRL(MSG_142),
LOC_CTRL(MSG_143),
LOC_CTRL(MSG_144),
LOC_CTRL(MSG_145),
LOC_CTRL(MSG_146),
LOC_CTRL(MSG_147),
LOC_CTRL(MSG_148),
LOC_CTRL(MSG_149),
LOC_CTRL(MSG_150),
LOC_CTRL(MSG_151),
LOC_CTRL(MSG_152),
LOC_CTRL(MSG_153),
LOC_CTRL(MSG_154),
LOC_CTRL(MSG_155),
LOC_CTRL(MSG_156),
LOC_CTRL(MSG_157),
LOC_CTRL(MSG_158),
LOC_CTRL(MSG_159),
LOC_CTRL(MSG_160),
LOC_CTRL(MSG_161),
LOC_CTRL(MSG_162),
LOC_CTRL(MSG_163),
LOC_CTRL(MSG_164),
LOC_CTRL(MSG_165),
LOC_CTRL(MSG_166),
LOC_CTRL(MSG_167),
LOC_CTRL(MSG_168),
LOC_CTRL(MSG_169),
LOC_CTRL(MSG_170),
LOC_CTRL(MSG_171),
LOC_CTRL(MSG_172),
LOC_CTRL(MSG_173),
LOC_CTRL(MSG_174),
LOC_CTRL(MSG_175),
LOC_CTRL(MSG_176),
LOC_CTRL(MSG_177),
LOC_CTRL(MSG_178),
LOC_CTRL(MSG_179),
LOC_CTRL(MSG_180),
LOC_CTRL(MSG_181),
LOC_CTRL(MSG_182),
LOC_CTRL(MSG_183),
LOC_CTRL(MSG_184),
LOC_CTRL(MSG_185),
LOC_CTRL(MSG_186),
LOC_CTRL(MSG_187),
LOC_CTRL(MSG_188),
LOC_CTRL(MSG_189),
LOC_CTRL(MSG_190),
LOC_CTRL(MSG_191),
LOC_CTRL(MSG_192),
LOC_CTRL(MSG_193),
LOC_CTRL(MSG_194),
LOC_CTRL(MSG_195),
LOC_CTRL(MSG_196),
LOC_CTRL(MSG_197),
LOC_CTRL(MSG_198),
LOC_CTRL(MSG_199),
LOC_CTRL(MSG_200),
LOC_CTRL(MSG_201),
LOC_CTRL(MSG_202),
LOC_CTRL(MSG_203),
LOC_CTRL(MSG_204),
LOC_CTRL(MSG_205),
LOC_CTRL(MSG_206),
LOC_CTRL(MSG_207),
LOC_CTRL(MSG_208),
LOC_CTRL(MSG_209),
LOC_CTRL(MSG_210),
LOC_CTRL(MSG_211),
LOC_CTRL(MSG_212),
LOC_CTRL(MSG_213),
LOC_CTRL(MSG_214),
LOC_CTRL(MSG_215),
LOC_CTRL(MSG_216),
LOC_CTRL(MSG_217),
LOC_CTRL(MSG_218),
LOC_CTRL(MSG_219),
LOC_CTRL(MSG_220),
LOC_CTRL(MSG_221),
LOC_CTRL(MSG_222),
LOC_CTRL(MSG_223),
LOC_CTRL(MSG_224),
LOC_CTRL(MSG_225),
LOC_CTRL(MSG_226),
LOC_CTRL(MSG_227),
LOC_CTRL(MSG_228),
LOC_CTRL(MSG_229),
LOC_CTRL(MSG_230),
LOC_CTRL(MSG_231),
LOC_CTRL(MSG_232),
LOC_CTRL(MSG_233),
LOC_CTRL(MSG_234),
LOC_CTRL(MSG_235),
LOC_CTRL(MSG_236),
LOC_CTRL(MSG_237),
LOC_CTRL(MSG_238),
LOC_CTRL(MSG_239),
LOC_CTRL(MSG_240),
LOC_CTRL(MSG_241),
LOC_CTRL(MSG_242),
LOC_CTRL(MSG_243),
LOC_CTRL(MSG_244),
LOC_CTRL(MSG_245),
LOC_CTRL(MSG_246),
LOC_CTRL(MSG_247),
LOC_CTRL(MSG_248),
LOC_CTRL(MSG_249),
LOC_CTRL(MSG_250),
LOC_CTRL(MSG_251),
LOC_CTRL(MSG_252),
LOC_CTRL(MSG_253),
LOC_CTRL(MSG_254),
LOC_CTRL(MSG_255),
LOC_CTRL(MSG_256),
LOC_CTRL(MSG_257),
LOC_CTRL(MSG_258),
LOC_CTRL(MSG_259),
LOC_CTRL(MSG_260),
LOC_CTRL(MSG_261),
LOC_CTRL(MSG_262),
LOC_CTRL(MSG_263),
LOC_CTRL(MSG_264),
LOC_CTRL(MSG_265),
LOC_CTRL(MSG_266),
LOC_CTRL(MSG_267),
LOC_CTRL(MSG_268),
LOC_CTRL(MSG_269),
LOC_CTRL(MSG_270),
LOC_CTRL(MSG_271),
LOC_CTRL(MSG_272),
LOC_CTRL(MSG_273),
LOC_CTRL(MSG_274),
LOC_CTRL(MSG_275),
LOC_CTRL(MSG_276),
LOC_CTRL(MSG_277),
LOC_CTRL(MSG_278),
LOC_CTRL(MSG_279),
LOC_CTRL(MSG_280),
LOC_CTRL(MSG_281),
LOC_CTRL(MSG_282),
LOC_CTRL(MSG_283),
LOC_CTRL(MSG_284),
LOC_CTRL(MSG_285),
LOC_CTRL(MSG_286),
LOC_CTRL(MSG_287),
LOC_CTRL(MSG_288),
LOC_CTRL(MSG_289),
LOC_CTRL(MSG_290),
LOC_CTRL(MSG_291),
LOC_CTRL(MSG_292),
LOC_CTRL(MSG_293),
LOC_CTRL(MSG_294),
LOC_CTRL(MSG_295),
LOC_CTRL(MSG_296),
LOC_CTRL(MSG_297),
LOC_CTRL(MSG_298),
LOC_CTRL(MSG_299),
LOC_CTRL(MSG_300),
LOC_CTRL(MSG_301),
LOC_CTRL(MSG_302),
LOC_CTRL(MSG_303),
LOC_CTRL(MSG_304),
LOC_CTRL(MSG_305),
LOC_CTRL(MSG_306),
LOC_CTRL(MSG_307),
LOC_CTRL(MSG_308),
LOC_CTRL(MSG_309),
LOC_CTRL(MSG_310),
LOC_CTRL(MSG_311),
LOC_CTRL(MSG_312),
LOC_CTRL(MSG_313),
LOC_CTRL(MSG_314),
LOC_CTRL(MSG_315),
LOC_CTRL(MSG_316),
LOC_CTRL(MSG_317),
LOC_CTRL(MSG_318),
LOC_CTRL(MSG_319),
LOC_CTRL(MSG_320),
LOC_CTRL(MSG_321),
LOC_CTRL(MSG_322),
LOC_CTRL(MSG_323),
LOC_CTRL(MSG_324),
LOC_CTRL(MSG_325),
LOC_CTRL(MSG_326),
LOC_CTRL(MSG_327),
LOC_CTRL(MSG_328),
LOC_CTRL(MSG_329),
LOC_CTRL(MSG_330),
LOC_CTRL(MSG_331),
LOC_CTRL(MSG_332),
LOC_CTRL(MSG_333),
LOC_CTRL(MSG_334),
LOC_CTRL(MSG_335),
LOC_CTRL(MSG_336),
LOC_CTRL(MSG_337),
LOC_CTRL(MSG_338),
LOC_CTRL(MSG_339),
LOC_CTRL(MSG_340),
LOC_CTRL(MSG_341),
LOC_CTRL(MSG_342),
LOC_CTRL(MSG_343),
LOC_CTRL(MSG_344),
LOC_CTRL(MSG_345),
LOC_CTRL(MSG_346),
LOC_CTRL(MSG_347),
LOC_CTRL(MSG_348),
LOC_CTRL(MSG_349),
LOC_CTRL(MSG_350),
LOC_CTRL(MSG_351),
LOC_CTRL(MSG_352),
LOC_CTRL(MSG_353),
LOC_CTRL(MSG_354),
LOC_CTRL(MSG_355),
LOC_CTRL(MSG_356),
LOC_CTRL(MSG_357),
LOC_CTRL(MSG_358),
LOC_CTRL(MSG_359),
LOC_CTRL(MSG_360),
LOC_CTRL(MSG_361),
LOC_CTRL(MSG_362),
LOC_CTRL(MSG_363),
LOC_CTRL(MSG_364),
LOC_CTRL(MSG_365),
LOC_CTRL(MSG_366),
LOC_CTRL(MSG_367),
LOC_CTRL(MSG_368),
LOC_CTRL(MSG_369),
LOC_CTRL(MSG_370),
LOC_CTRL(MSG_371),
LOC_CTRL(MSG_372),
LOC_CTRL(MSG_373),
LOC_CTRL(MSG_374),
LOC_CTRL(MSG_375),
LOC_CTRL(MSG_376),
LOC_CTRL(MSG_377),
LOC_CTRL(MSG_378),
LOC_CTRL(MSG_379),
LOC_CTRL(MSG_380),
LOC_CTRL(MSG_381),
LOC_CTRL(MSG_382),
LOC_CTRL(MSG_383),
LOC_CTRL(MSG_384),
LOC_CTRL(MSG_385),
LOC_CTRL(MSG_386),
LOC_CTRL(MSG_387),
LOC_CTRL(MSG_388),
LOC_CTRL(MSG_389),
LOC_CTRL(MSG_390),
LOC_CTRL(MSG_391),
LOC_CTRL(MSG_392),
LOC_CTRL(MSG_393),
LOC_CTRL(MSG_394),
LOC_CTRL(MSG_395),
LOC_CTRL(MSG_396),
LOC_CTRL(MSG_397),
LOC_CTRL(MSG_398),
LOC_CTRL(MSG_399),
LOC_CTRL(MSG_MAX),
LOC_CTRL(IDOK),
LOC_CTRL(IDCANCEL),
LOC_CTRL(IDABORT),
LOC_CTRL(IDRETRY),
LOC_CTRL(IDIGNORE),
LOC_CTRL(IDYES),
LOC_CTRL(IDNO),
LOC_CTRL(IDCLOSE),
LOC_CTRL(IDHELP),
};
// Dialog data
loc_dlg_list loc_dlg[] = {
LOC_DLG(IDD_DIALOG),
LOC_DLG(IDD_ABOUTBOX),
LOC_DLG(IDD_NOTIFICATION),
LOC_DLG(IDD_SELECTION),
LOC_DLG(IDD_LICENSE),
LOC_DLG(IDD_LOG),
LOC_DLG(IDD_UPDATE_POLICY),
LOC_DLG(IDD_NEW_VERSION),
LOC_DLG(IDD_HASH),
LOC_DLG(IDD_LIST),
};
| 13,388 |
C
|
.c
| 581 | 21.056799 | 72 | 0.71038 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
4,660 |
cpu.c
|
pbatard_rufus/src/cpu.c
|
/*
* Rufus: The Reliable USB Formatting Utility
* CPU features detection
* Copyright © 2022 Pete Batard <[email protected]>
* Copyright © 2022 Jeffrey Walton <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "cpu.h"
#if (defined(CPU_X86_SHA1_ACCELERATION) || defined(CPU_X86_SHA256_ACCELERATION))
#if defined(RUFUS_MSC_VERSION)
#include <intrin.h>
#elif (defined(RUFUS_GCC_VERSION) || defined(RUFUS_CLANG_VERSION))
#include <x86Intrin.h>
#elif defined(RUFUS_INTEL_VERSION)
#include <immintrin.h>
#endif
#endif
BOOL cpu_has_sha1_accel = FALSE;
BOOL cpu_has_sha256_accel = FALSE;
/*
* Three elements must be in place to make a meaningful call to the
* DetectSHA###Acceleration() calls. First, the compiler must support
* the underlying intrinsics. Second, the platform must provide a
* cpuid() function. And third, the cpu must actually support the SHA-1
* and SHA-256 instructions.
*
* If any of the conditions are not met, then DetectSHA###Acceleration()
* returns FALSE.
*/
/*
* Detect if the processor supports SHA-1 acceleration. We only check for
* the three ISAs we need - SSSE3, SSE4.1 and SHA. We don't check for OS
* support or XSAVE because that's been enabled since Windows 2000.
*/
BOOL DetectSHA1Acceleration(void)
{
#if defined(CPU_X86_SHA1_ACCELERATION)
#if defined(_MSC_VER)
uint32_t regs0[4] = {0,0,0,0}, regs1[4] = {0,0,0,0}, regs7[4] = {0,0,0,0};
const uint32_t SSSE3_BIT = 1u << 9; /* Function 1, Bit 9 of ECX */
const uint32_t SSE41_BIT = 1u << 19; /* Function 1, Bit 19 of ECX */
const uint32_t SHA_BIT = 1u << 29; /* Function 7, Bit 29 of EBX */
__cpuid(regs0, 0);
const uint32_t highest = regs0[0]; /*EAX*/
if (highest >= 0x01) {
__cpuidex(regs1, 1, 0);
}
if (highest >= 0x07) {
__cpuidex(regs7, 7, 0);
}
return (regs1[2] /*ECX*/ & SSSE3_BIT) && (regs1[2] /*ECX*/ & SSE41_BIT) && (regs7[1] /*EBX*/ & SHA_BIT) ? TRUE : FALSE;
#elif defined(__GNUC__) || defined(__clang__)
/* __builtin_cpu_supports available in GCC 4.8.1 and above */
return __builtin_cpu_supports("ssse3") && __builtin_cpu_supports("sse4.1") && __builtin_cpu_supports("sha") ? TRUE : FALSE;
#elif defined(__INTEL_COMPILER)
/* https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_may_i_use_cpu_feature */
return _may_i_use_cpu_feature(_FEATURE_SSSE3|_FEATURE_SSE4_1|_FEATURE_SHA) ? TRUE : FALSE;
#else
return FALSE;
#endif
#else
return FALSE;
#endif
}
/*
* Detect if the processor supports SHA-256 acceleration. We only check for
* the three ISAs we need - SSSE3, SSE4.1 and SHA. We don't check for OS
* support or XSAVE because that's been enabled since Windows 2000.
*/
BOOL DetectSHA256Acceleration(void)
{
#if defined(CPU_X86_SHA256_ACCELERATION)
#if defined(_MSC_VER)
uint32_t regs0[4] = {0,0,0,0}, regs1[4] = {0,0,0,0}, regs7[4] = {0,0,0,0};
const uint32_t SSSE3_BIT = 1u << 9; /* Function 1, Bit 9 of ECX */
const uint32_t SSE41_BIT = 1u << 19; /* Function 1, Bit 19 of ECX */
const uint32_t SHA_BIT = 1u << 29; /* Function 7, Bit 29 of EBX */
__cpuid(regs0, 0);
const uint32_t highest = regs0[0]; /*EAX*/
if (highest >= 0x01) {
__cpuidex(regs1, 1, 0);
}
if (highest >= 0x07) {
__cpuidex(regs7, 7, 0);
}
return (regs1[2] /*ECX*/ & SSSE3_BIT) && (regs1[2] /*ECX*/ & SSE41_BIT) && (regs7[1] /*EBX*/ & SHA_BIT) ? TRUE : FALSE;
#elif defined(__GNUC__) || defined(__clang__)
/* __builtin_cpu_supports available in GCC 4.8.1 and above */
return __builtin_cpu_supports("ssse3") && __builtin_cpu_supports("sse4.1") && __builtin_cpu_supports("sha") ? TRUE : FALSE;
#elif defined(__INTEL_COMPILER)
/* https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_may_i_use_cpu_feature */
return _may_i_use_cpu_feature(_FEATURE_SSSE3|_FEATURE_SSE4_1|_FEATURE_SHA) ? TRUE : FALSE;
#else
return FALSE;
#endif
#else
return FALSE;
#endif
}
| 4,476 |
C
|
.c
| 111 | 38.504505 | 124 | 0.698 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
4,666 |
smart.c
|
pbatard_rufus/src/smart.c
|
/*
* Rufus: The Reliable USB Formatting Utility
* SMART HDD vs Flash detection (using ATA over USB, S.M.A.R.T., etc.)
* Copyright © 2013-2023 Pete Batard <[email protected]>
*
* Based in part on scsiata.cpp from Smartmontools: http://smartmontools.sourceforge.net
* Copyright © 2006-2012 Douglas Gilbert <[email protected]>
* Copyright © 2009-2013 Christian Franke <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stddef.h>
#include "rufus.h"
#include "missing.h"
#include "msapi_utf8.h"
#include "drive.h"
#include "smart.h"
#include "hdd_vs_ufd.h"
#if defined(RUFUS_TEST)
/* Helper functions */
static uint8_t GetAtaDirection(uint8_t AtaCmd, uint8_t Features) {
// Far from complete -- only the commands we *may* use.
// Most SMART commands require DATA_IN but there are a couple exceptions
BOOL smart_out = (AtaCmd == ATA_SMART_CMD) &&
((Features == ATA_SMART_STATUS) || (Features == ATA_SMART_WRITE_LOG_SECTOR));
switch (AtaCmd) {
case ATA_IDENTIFY_DEVICE:
case ATA_READ_LOG_EXT:
return ATA_PASSTHROUGH_DATA_IN;
case ATA_SMART_CMD:
if (!smart_out)
return ATA_PASSTHROUGH_DATA_IN;
// fall through
case ATA_DATA_SET_MANAGEMENT:
return ATA_PASSTHROUGH_DATA_OUT;
default:
return ATA_PASSTHROUGH_DATA_NONE;
}
}
const char* SptStrerr(int errcode)
{
static char scsi_err[64];
if ((errcode > 0) && (errcode <= 0xff)) {
static_sprintf(scsi_err, "SCSI status: 0x%02X", (uint8_t)errcode);
return (const char*)scsi_err;
}
switch(errcode) {
case SPT_SUCCESS:
return "Success";
case SPT_ERROR_CDB_LENGTH:
return "Invalid CDB length";
case SPT_ERROR_BUFFER:
return "Buffer must be aligned to a page boundary and less than 64KB in size";
case SPT_ERROR_DIRECTION:
return "Invalid Direction";
case SPT_ERROR_EXTENDED_CDB:
return "Extended and variable length CDB commands are not supported";
case SPT_ERROR_CDB_OPCODE:
return "Opcodes above 0xC0 are not supported";
case SPT_ERROR_TIMEOUT:
return "Timeout";
case SPT_ERROR_INVALID_PARAMETER:
return "Invalid DeviceIoControl parameter";
case SPT_ERROR_CHECK_STATUS:
return "SCSI error (check Status)";
default:
return "Unknown error";
}
}
/*
* SCSI Passthrough (using IOCTL_SCSI_PASS_THROUGH_DIRECT)
* Should be provided a handle to the physical device (R/W) as well as a Cdb and a buffer that is page aligned
* Direction should be one of SCSI_IOCTL_DATA_###
*
* Returns 0 (SPT_SUCCESS) on success, a positive SCSI Status in case of an SCSI error or negative otherwise.
*/
BOOL ScsiPassthroughDirect(HANDLE hPhysical, uint8_t* Cdb, size_t CdbLen, uint8_t Direction,
void* DataBuffer, size_t BufLen, uint32_t Timeout)
{
SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER sptdwb = {{0}, 0, {0}};
DWORD err, size = sizeof(SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER);
BOOL r;
// Sanity checks
if ((CdbLen == 0) || (CdbLen > sizeof(sptdwb.sptd.Cdb)))
return SPT_ERROR_CDB_LENGTH;
if (((uintptr_t)DataBuffer % 0x10 != 0) || (BufLen > 0xFFFF))
return SPT_ERROR_BUFFER;
if (Direction > SCSI_IOCTL_DATA_UNSPECIFIED)
return SPT_ERROR_DIRECTION;
// http://en.wikipedia.org/wiki/SCSI_command
if ((Cdb[0] == 0x7e) || (Cdb[0] == 0x7f))
return SPT_ERROR_EXTENDED_CDB;
// Opcodes above 0xC0 are unsupported (apart for the special JMicron/Sunplus modes)
if ( (Cdb[0] >= 0xc0) && (Cdb[0] != USB_JMICRON_ATA_PASSTHROUGH)
&& (Cdb[0] != USB_SUNPLUS_ATA_PASSTHROUGH) )
return SPT_ERROR_CDB_OPCODE;
sptdwb.sptd.Length = sizeof(SCSI_PASS_THROUGH_DIRECT);
sptdwb.sptd.PathId = 0;
sptdwb.sptd.TargetId = 0;
sptdwb.sptd.Lun = 0;
sptdwb.sptd.CdbLength = (uint8_t)CdbLen;
sptdwb.sptd.DataIn = Direction; // One of SCSI_IOCTL_DATA_###
sptdwb.sptd.SenseInfoLength = SPT_SENSE_LENGTH;
sptdwb.sptd.DataTransferLength = (uint16_t)BufLen;
sptdwb.sptd.TimeOutValue = Timeout;
sptdwb.sptd.DataBuffer = DataBuffer;
sptdwb.sptd.SenseInfoOffset = offsetof(SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, SenseBuf);
memcpy(sptdwb.sptd.Cdb, Cdb, CdbLen);
r = DeviceIoControl(hPhysical, IOCTL_SCSI_PASS_THROUGH_DIRECT, &sptdwb, size, &sptdwb, size, &size, FALSE);
if ((r) && (sptdwb.sptd.ScsiStatus == 0)) {
return SPT_SUCCESS;
}
if (sptdwb.sptd.ScsiStatus != 0) {
// uprintf("ScsiPassthroughDirect: CDB command 0x%02X failed (SCSI status 0x%02X)\n", Cdb[0], sptdwb.sptd.ScsiStatus);
return (int)sptdwb.sptd.ScsiStatus;
} else {
err = GetLastError();
// uprintf("ScsiPassthroughDirect: CDB command 0x%02X failed %s\n", Cdb[0], WindowsErrorString()); SetLastError(err);
switch(err) {
case ERROR_SEM_TIMEOUT:
return SPT_ERROR_TIMEOUT;
case ERROR_INVALID_PARAMETER:
return SPT_ERROR_INVALID_PARAMETER;
default:
return SPT_ERROR_UNKNOWN_ERROR;
}
}
return FALSE;
}
/* See ftp://ftp.t10.org/t10/document.04/04-262r8.pdf, http://www.scsitoolbox.com/pdfs/UsingSAT.pdf,
* as well as http://nevar.pl/pliki/ATA8-ACS-3.pdf */
static int SatAtaPassthrough(HANDLE hPhysical, ATA_PASSTHROUGH_CMD* Command, void* DataBuffer, size_t BufLen, uint32_t Timeout)
{
uint8_t Cdb[12] = {0};
int extend = 0; /* For 48-bit ATA command (unused here) */
int ck_cond = 0; /* Set to 1 to read register(s) back */
int protocol = 3; /* Non-data */
int t_dir = 1; /* 0 -> to device, 1 -> from device */
int byte_block = 1; /* 0 -> bytes, 1 -> 512 byte blocks */
int t_length = 0; /* 0 -> no data transferred */
uint8_t Direction;
if (BufLen % SelectedDrive.SectorSize != 0) {
uprintf("SatAtaPassthrough: BufLen must be a multiple of <block size>\n");
return SPT_ERROR_BUFFER;
}
// Set data direction
Direction = GetAtaDirection(Command->AtaCmd, Command->Features);
if (BufLen != 0) {
switch (Direction) {
case ATA_PASSTHROUGH_DATA_NONE:
break;
case ATA_PASSTHROUGH_DATA_IN:
protocol = 4; // PIO data-in
t_length = 2; // The transfer length is specified in the sector_count field
break;
case ATA_PASSTHROUGH_DATA_OUT:
protocol = 5; // PIO data-out
t_length = 2; // The transfer length is specified in the sector_count field
t_dir = 0; // to device
break;
}
}
Cdb[0] = SAT_ATA_PASSTHROUGH_12;
Cdb[1] = (protocol << 1) | extend;
Cdb[2] = (ck_cond << 5) | (t_dir << 3) | (byte_block << 2) | t_length;
Cdb[3] = Command->Features;
Cdb[4] = (uint8_t)(BufLen >> SECTOR_SIZE_SHIFT_BIT);
Cdb[5] = Command->Lba_low;
Cdb[6] = Command->Lba_mid;
Cdb[7] = Command->Lba_high;
Cdb[8] = Command->Device; // (m_port == 0 ? 0xa0 : 0xb0); // Must be 0 for identify
Cdb[9] = Command->AtaCmd;
return ScsiPassthroughDirect(hPhysical, Cdb, sizeof(Cdb), Direction, DataBuffer, BufLen, Timeout);
}
/* The only differences between JMicron and Prolific are the extra 2 bytes for the CDB */
static int _UsbJMPLAtaPassthrough(HANDLE hPhysical, ATA_PASSTHROUGH_CMD* Command,
void* DataBuffer, size_t BufLen, uint32_t Timeout, BOOL prolific)
{
uint8_t Cdb[14] = {0};
uint8_t Direction;
Direction = GetAtaDirection(Command->AtaCmd, Command->Features);
Cdb[0] = USB_JMICRON_ATA_PASSTHROUGH;
Cdb[1] = ((BufLen != 0) && (Direction == ATA_PASSTHROUGH_DATA_OUT))?0x00:0x10;
Cdb[3] = (uint8_t)(BufLen >> 8);
Cdb[4] = (uint8_t)(BufLen);
Cdb[5] = Command->Features;
Cdb[6] = (uint8_t)(BufLen >> SECTOR_SIZE_SHIFT_BIT);
Cdb[7] = Command->Lba_low;
Cdb[8] = Command->Lba_mid;
Cdb[9] = Command->Lba_high;
Cdb[10] = Command->Device; // (m_port == 0 ? 0xa0 : 0xb0); // Must be 0 for identify
Cdb[11] = Command->AtaCmd;
// Prolific PL3507
Cdb[12] = 0x06;
Cdb[13] = 0x7b;
return ScsiPassthroughDirect(hPhysical, Cdb, sizeof(Cdb)-(prolific?2:0), Direction, DataBuffer, BufLen, Timeout);
}
static int UsbJmicronAtaPassthrough(HANDLE hPhysical, ATA_PASSTHROUGH_CMD* Command, void* DataBuffer, size_t BufLen, uint32_t Timeout)
{
return _UsbJMPLAtaPassthrough(hPhysical, Command, DataBuffer, BufLen, Timeout, FALSE);
}
/* UNTESTED!!! */
static int UsbProlificAtaPassthrough(HANDLE hPhysical, ATA_PASSTHROUGH_CMD* Command, void* DataBuffer, size_t BufLen, uint32_t Timeout)
{
return _UsbJMPLAtaPassthrough(hPhysical, Command, DataBuffer, BufLen, Timeout, TRUE);
}
/* UNTESTED!!! */
static int UsbSunPlusAtaPassthrough(HANDLE hPhysical, ATA_PASSTHROUGH_CMD* Command, void* DataBuffer, size_t BufLen, uint32_t Timeout)
{
uint8_t Cdb[12] = {0};
uint8_t Direction;
Direction = GetAtaDirection(Command->AtaCmd, Command->Features);
Cdb[0] = USB_SUNPLUS_ATA_PASSTHROUGH;
Cdb[2] = 0x22;
if (BufLen != 0) {
if (Direction == ATA_PASSTHROUGH_DATA_IN)
Cdb[3] = 0x10;
else if (Direction == ATA_PASSTHROUGH_DATA_OUT)
Cdb[3] = 0x11;
}
Cdb[4] = (uint8_t)(BufLen >> SECTOR_SIZE_SHIFT_BIT);
Cdb[5] = Command->Features;
Cdb[6] = (uint8_t)(BufLen >> SECTOR_SIZE_SHIFT_BIT);
Cdb[7] = Command->Lba_low;
Cdb[8] = Command->Lba_mid;
Cdb[9] = Command->Lba_high;
Cdb[10] = Command->Device | 0xa0;
Cdb[11] = Command->AtaCmd;
return ScsiPassthroughDirect(hPhysical, Cdb, sizeof(Cdb), Direction, DataBuffer, BufLen, Timeout);
}
/* UNTESTED!!! */
/* See: http://kernel.opensuse.org/cgit/kernel/tree/drivers/usb/storage/cypress_atacb.c */
static int UsbCypressAtaPassthrough(HANDLE hPhysical, ATA_PASSTHROUGH_CMD* Command, void* DataBuffer, size_t BufLen, uint32_t Timeout)
{
uint8_t Cdb[16] = {0};
uint8_t Direction;
Direction = GetAtaDirection(Command->AtaCmd, Command->Features);
Cdb[0] = USB_CYPRESS_ATA_PASSTHROUGH;
Cdb[1] = USB_CYPRESS_ATA_PASSTHROUGH;
if (Command->AtaCmd == ATA_IDENTIFY_DEVICE || Command->AtaCmd == ATA_IDENTIFY_PACKET_DEVICE)
Cdb[2] = (1<<7); // Set IdentifyPacketDevice
Cdb[3] = 0xff - (1<<0) - (1<<6); // Features, sector count, lba low, lba med, lba high
Cdb[4] = 1; // Units in blocks rather than bytes
Cdb[6] = Command->Features;
Cdb[7] = (uint8_t)(BufLen >> SECTOR_SIZE_SHIFT_BIT);
Cdb[8] = Command->Lba_low;
Cdb[9] = Command->Lba_mid;
Cdb[10] = Command->Lba_high;
Cdb[11] = Command->Device;
Cdb[12] = Command->AtaCmd;
return ScsiPassthroughDirect(hPhysical, Cdb, sizeof(Cdb), Direction, DataBuffer, BufLen, Timeout);
}
/* The various bridges we will try, in order */
AtaPassThroughType ata_pt[] = {
{ SatAtaPassthrough, "SAT" },
{ UsbJmicronAtaPassthrough, "JMicron" },
{ UsbProlificAtaPassthrough, "Prolific" },
{ UsbSunPlusAtaPassthrough, "SunPlus" },
{ UsbCypressAtaPassthrough, "Cypress" },
};
BOOL Identify(HANDLE hPhysical)
{
ATA_PASSTHROUGH_CMD Command = {0};
IDENTIFY_DEVICE_DATA* idd;
int i, r;
Command.AtaCmd = ATA_IDENTIFY_DEVICE;
// You'll get an error here if your compiler does not properly pack the IDENTIFY struct
COMPILE_TIME_ASSERT(sizeof(IDENTIFY_DEVICE_DATA) == 512);
idd = (IDENTIFY_DEVICE_DATA*)_mm_malloc(sizeof(IDENTIFY_DEVICE_DATA), 0x10);
if (idd == NULL)
return FALSE;
for (i=0; i<ARRAYSIZE(ata_pt); i++) {
r = ata_pt[i].fn(hPhysical, &Command, idd, sizeof(IDENTIFY_DEVICE_DATA), SPT_TIMEOUT_VALUE);
if (r == SPT_SUCCESS) {
uprintf("Success using %s\n", ata_pt[i].type);
if (idd->CommandSetSupport.SmartCommands) {
DumpBufferHex(idd, sizeof(IDENTIFY_DEVICE_DATA));
uprintf("SMART support detected!\n");
} else {
uprintf("No SMART support\n");
}
break;
}
uprintf("No joy with: %s (%s)\n", ata_pt[i].type, SptStrerr(r));
}
if (i >= ARRAYSIZE(ata_pt))
uprintf("NO ATA FOR YOU!\n");
_mm_free(idd);
return TRUE;
}
#endif
/* Generic SMART access. Kept for reference, as it doesn't work for USB to ATA/SATA bridges */
#if 0
#pragma pack(1)
typedef struct {
UCHAR bVersion;
UCHAR bRevision;
UCHAR bReserved;
UCHAR bIDEDeviceMap;
ULONG fCapabilities;
ULONG dwReserved[4];
} MY_GETVERSIONINPARAMS;
#pragma pack()
#ifndef SMART_GET_VERSION
#define SMART_GET_VERSION \
CTL_CODE(IOCTL_DISK_BASE, 0x0020, METHOD_BUFFERED, FILE_READ_ACCESS)
#endif
BOOL SmartGetVersion(HANDLE hdevice)
{
MY_GETVERSIONINPARAMS vers;
DWORD size = sizeof(MY_GETVERSIONINPARAMS);
BOOL r;
memset(&vers, 0, sizeof(vers));
r = DeviceIoControl(hdevice, SMART_GET_VERSION, NULL, 0, &vers, sizeof(vers), &size, NULL);
if ( (!r) || (size != sizeof(MY_GETVERSIONINPARAMS)) ) {
uprintf("SmartGetVersion failed: %s\n", r?"unexpected size":WindowsErrorString());
return FALSE;
}
uprintf("Smart Version: %d.%d, Caps = 0x%x, DeviceMap = 0x%02x\n",
vers.bVersion, vers.bRevision, (unsigned)vers.fCapabilities, vers.bIDEDeviceMap);
return vers.bIDEDeviceMap;
}
#endif
/*
* This attempts to detect whether a drive is an USB HDD or an USB Flash Drive (UFD).
* A positive score means that we think it's an USB HDD, zero or negative means that
* we think it's an UFD.
*
* This is done so that, if someone already has an USB HDD plugged in (say as a
* backup drive) and plugs an UFD we *try* to do what we can to avoid them formatting
* that drive by mistake.
* However, because there is no foolproof (let alone easy) way to differentiate UFDs
* from HDDs, thanks to every manufacturer, Microsoft, and their mothers, making it
* exceedingly troublesome to find what type of hardware we are actually accessing,
* you are expected to pay heed to the following:
*
* WARNING: NO PROMISE IS MADE ABOUT THIS ALGORITHM BEING ABLE TO CORRECTLY
* DIFFERENTIATE AN USB HDD FROM AN USB FLASH DRIVE. MOREOVER, YOU ARE REMINDED THAT
* THE LICENSE OF THIS APPLICATION MAKES NO PROMISE ABOUT AVOIDING DATA LOSS EITHER
* (PROVIDED "AS IS").
* THUS, IF DATA LOSS IS INCURRED DUE TO THIS, OR ANY OTHER PART OF THIS APPLICATION,
* NOT BEHAVING IN THE MANNER YOU EXPECTED, THE RESPONSIBILITY IS ENTIRELY ON YOU!
*
* What you have below, then, is our *current best guess* at differentiating UFDs
* from HDDs. But short of a crystal ball, this remains just a guess, which may be
* way off mark. Still, you are also reminded that Rufus does produce PROMINENT
* warnings before you format a drive, and also provides extensive info about the
* drive (from the tooltips and the log) => PAY ATTENTION TO THESE OR PAY THE PRICE!
*
* But let me just elaborate further on why differentiating UFDs from HDDs is not as
* 'simple' as it seems:
* - many USB flash drives manufacturer will present UFDs as non-removable, which used
* to be reserved for HDDs => we can't use that as differentiator.
* - some UFDs (SanDisk Extreme) have added S.M.A.R.T. support, which also used to be
* reserved for HDDs => can't use that either
* - even if S.M.A.R.T. was enough, not all USB->IDE or USB->SATA bridges support ATA
* passthrough, which is required S.M.A.R.T. data, and each manufacturer of an
* USB<->(S)ATA bridge seem to have their own method of implementing passthrough.
* - SSDs have also changed the deal completely, as you can get something that looks
* like Flash but that is really an HDD.
* - Some manufacturers (eg. Verbatim) provide both USB Flash Drives and USB HDDs, so
* we can't exactly use the VID to say for sure what we're looking at.
* - Finally, Microsoft is absolutely no help either (which is kind of understandable
* from the above) => there is no magic API we can query that will tell us what we're
* really looking at.
*/
int IsHDD(DWORD DriveIndex, uint16_t vid, uint16_t pid, const char* strid)
{
int score = 0;
size_t i, mlen, ilen, score_list_size = 0;
BOOL wc;
uint64_t drive_size;
int8_t score_list[16];
char str[64] = { 0 };
// Boost the score if fixed, as these are *generally* HDDs
if (GetDriveTypeFromIndex(DriveIndex) == DRIVE_FIXED) {
score_list[score_list_size] = 3;
score += score_list[score_list_size++];
}
// Adjust the score depending on the size
drive_size = GetDriveSize(DriveIndex);
if (drive_size > 800 * GB) {
score_list[score_list_size] = 15;
score += score_list[score_list_size++];
if (drive_size > 1800 * GB) {
score_list[score_list_size] = 15;
score += score_list[score_list_size++];
}
} else if (drive_size < 128 * GB) {
score_list[score_list_size] = -15;
score += score_list[score_list_size++];
}
// Check the string against well known HDD identifiers
if (strid != NULL) {
ilen = strlen(strid);
for (i = 0; i < ARRAYSIZE(str_score); i++) {
mlen = strlen(str_score[i].name);
if (mlen > ilen)
break;
wc = (str_score[i].name[mlen-1] == '#');
if ( (_strnicmp(strid, str_score[i].name, mlen-((wc)?1:0)) == 0)
&& ((!wc) || ((strid[mlen] >= '0') && (strid[mlen] <= '9'))) ) {
score_list[score_list_size] = str_score[i].score;
score += score_list[score_list_size++];
break;
}
}
}
// Adjust for oddball devices
if (strid != NULL) {
for (i = 0; i < ARRAYSIZE(str_adjust); i++)
if (StrStrIA(strid, str_adjust[i].name) != NULL) {
score_list[score_list_size] = str_adjust[i].score;
score += score_list[score_list_size++];
}
}
// Check against known VIDs
for (i = 0; i < ARRAYSIZE(vid_score); i++) {
if (vid == vid_score[i].vid) {
score_list[score_list_size] = vid_score[i].score;
score += score_list[score_list_size++];
break;
}
}
// Check against known VID:PIDs
for (i = 0; i < ARRAYSIZE(vidpid_score); i++) {
if ((vid == vidpid_score[i].vid) && (pid == vidpid_score[i].pid)) {
score_list[score_list_size] = vidpid_score[i].score;
score += score_list[score_list_size++];
break;
}
}
// Print a breakdown of the device score if requested
if (usb_debug) {
static_strcat(str, "Device score: ");
for (i = 0; i < score_list_size; i++)
safe_sprintf(&str[strlen(str)], sizeof(str) - strlen(str), "%+d", score_list[i]);
uprintf("%s=%+d → Detected as %s", str, score, (score > 0) ? "HDD" : "UFD");
}
return score;
}
| 18,255 |
C
|
.c
| 460 | 37.295652 | 135 | 0.708886 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
4,675 |
localization.h
|
pbatard_rufus/src/localization.h
|
/*
* Rufus: The Reliable USB Formatting Utility
* Localization functions, a.k.a. "Everybody is doing it wrong but me!"
* Copyright © 2013-2016 Pete Batard <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdint.h>
#include <stddef.h>
#pragma once
// Number of concurrent localization messages (i.e. messages we can concurrently
// reference at the same time). Must be a power of 2.
#define LOC_MESSAGE_NB 32
#define LOC_MESSAGE_SIZE 2048
#define LOC_HTAB_SIZE 1031 // Using a prime speeds up the hash table init
// Attributes that can be set by a translation
#define LOC_RIGHT_TO_LEFT 0x00000001
#define LOC_NEEDS_UPDATE 0x00000002
#define MSG_RTF 0x10000000
#define MSG_MASK 0x0FFFFFFF
#define luprint(msg) uprintf("%s(%d): " msg "\n", loc_filename, loc_line_nr)
#define luprintf(msg, ...) uprintf("%s(%d): " msg "\n", loc_filename, loc_line_nr, __VA_ARGS__)
/*
* List handling functions (stolen from libusb)
* NB: offsetof() requires '#include <stddef.h>'
*/
struct list_head {
struct list_head *prev, *next;
};
/* Get an entry from the list
* ptr - the address of this list_head element in "type"
* type - the data type that contains "member"
* member - the list_head element in "type"
*/
#define list_entry(ptr, type, member) \
((type *)((uintptr_t)(ptr) - (uintptr_t)offsetof(type, member)))
/* Get each entry from a list
* pos - A structure pointer has a "member" element
* head - list head
* member - the list_head element in "pos"
* type - the type of the first parameter
*/
#define list_for_each_entry(pos, head, type, member) \
for (pos = list_entry((head)->next, type, member); \
&pos->member != (head); \
pos = list_entry(pos->member.next, type, member))
#define list_for_each_entry_safe(pos, n, head, type, member) \
for (pos = list_entry((head)->next, type, member), \
n = list_entry(pos->member.next, type, member); \
&pos->member != (head); \
pos = n, n = list_entry(n->member.next, type, member))
#define list_empty(entry) ((entry)->next == (entry))
static __inline void list_init(struct list_head *entry)
{
entry->prev = entry->next = entry;
}
static __inline void list_add(struct list_head *entry, struct list_head *head)
{
entry->next = head->next;
entry->prev = head;
head->next->prev = entry;
head->next = entry;
}
static __inline void list_add_tail(struct list_head *entry,
struct list_head *head)
{
entry->next = head;
entry->prev = head->prev;
head->prev->next = entry;
head->prev = entry;
}
static __inline void list_del(struct list_head *entry)
{
entry->next->prev = entry->prev;
entry->prev->next = entry->next;
entry->next = entry->prev = NULL;
}
// Commands that take a control ID *MUST* be at the top
// The last command with a control ID *MUST* be LC_TEXT
enum loc_command_type {
LC_GROUP,
LC_TEXT, // Delimits commands that take a Control ID and commands that don't
LC_VERSION,
LC_LOCALE,
LC_BASE,
LC_FONT,
LC_ATTRIBUTES,
};
typedef struct loc_cmd_struct {
uint8_t command;
uint8_t unum_size;
uint16_t line_nr;
int ctrl_id; // Also used as the attributes mask
int32_t num[2];
uint32_t* unum;
char* txt[2];
struct list_head list;
} loc_cmd;
typedef struct loc_parse_struct {
char c;
enum loc_command_type cmd;
char* arg_type;
} loc_parse;
typedef struct loc_control_id_struct {
const char* name;
const int id;
} loc_control_id;
typedef struct loc_dlg_list_struct {
const int dlg_id;
HWND hDlg;
struct list_head list;
} loc_dlg_list;
extern const loc_parse parse_cmd[7];
extern struct list_head locale_list;
extern char *default_msg_table[], *current_msg_table[], **msg_table;
extern int loc_line_nr;
extern char *loc_filename, *embedded_loc_filename;
extern BOOL en_msg_mode;
void free_loc_cmd(loc_cmd* lcmd);
BOOL dispatch_loc_cmd(loc_cmd* lcmd);
void _init_localization(BOOL reinit);
void _exit_localization(BOOL reinit);
#define init_localization() _init_localization(FALSE)
#define exit_localization() _exit_localization(FALSE)
#define reinit_localization() do {_exit_localization(TRUE); _init_localization(TRUE);} while(0)
void apply_localization(int dlg_id, HWND hDlg);
void reset_localization(int dlg_id);
void free_dialog_list(void);
char* lmprintf(uint32_t msg_id, ...);
BOOL get_supported_locales(const char* filename);
BOOL get_loc_data_file(const char* filename, loc_cmd* lcmd);
void free_locale_list(void);
loc_cmd* get_locale_from_lcid(int lcid, BOOL fallback);
loc_cmd* get_locale_from_name(char* locale_name, BOOL fallback);
void toggle_default_locale(void);
const char* get_name_from_id(int id);
WORD get_language_id(loc_cmd* lcmd);
| 5,313 |
C
|
.c
| 148 | 34.162162 | 95 | 0.714786 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,678 |
dos_locale.c
|
pbatard_rufus/src/dos_locale.c
|
/*
* Rufus: The Reliable USB Formatting Utility
* DOS keyboard locale setup
* Copyright © 2011-2024 Pete Batard <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* Memory leaks detection - define _CRTDBG_MAP_ALLOC as preprocessor macro */
#ifdef _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "rufus.h"
#if defined(_MSC_VER)
// We have a bunch of \xCD characters in this file that MS doesn't like
#pragma warning(disable: 4819)
#endif
/*
* Note: if you want a book that can be used as a keyboards and codepages bible, I
* would recommend the "OS/2 Warp Server for e-business - Keyboards and Codepages".
* See http://www.borgendale.com/keyboard.pdf
*/
/* WinME DOS keyboard 2 letter codes & supported keyboard ID(s), as retrieved
* from the Millennium disk image in diskcopy.dll on a Windows 7 system
*
* KEYBOARD.SYS
* GR 129*
* SP 172
* PO 163*
* FR 120*, 189*
* DK 159*
* SG 000*
* IT 141*, 142*
* UK 166*, 168*
* SF 150*
* BE 120*
* NL 143*
* NO 155*
* CF 058*
* SV 153*
* SU 153
* LA 171*
* BR 274*
* PL 214*
* CZ 243*
* SL 245*
* YU 234*
* HU 208*
* US/XX 103*
* JP defines ID:194 but points to SP entry
*
* KEYBRD2.SYS
* GR 129*
* RU 441
* IT 141*, 142*
* UK 166*, 168*
* NO 155*
* CF 058*
* SV 153*
* SU 153
* BR 274*, 275*
* BG 442*
* PL 214*
* CZ 243*
* SL 245*
* YU 234*
* YC 118
* HU 208*
* RO 333
* IS 161*
* TR 179*, 440*
* GK 319*
* US/XX 103*
*
* KEYBRD3.SYS
* GR 129*
* SP 172*
* FR 189*
* DK 159*
* SG 000*
* IT 141*
* UK 166*
* SF 150*
* BE 120*
* NL 143*
* SV 153*
* SU 153
* PL 214*
* CZ 243*
* SL 245*
* YU 234*
* HU 208*
* RU 091*, 092*, 093*, 341*
* UR 094*, 095*, 096*
* BL 097*, 098*, 099*
* US/XX 103*
* JP defines ID:194 but points to SP entry
*
* KEYBRD4.SYS
* GK 101*, 319*, 220*
* PL 214*
* ET 425*
* HE 400*
* AR 401*, 402*, 403*
* US/XX 103*
*/
/*
* The following lists the keyboard code that are supported in each
* of the WinMe DOS KEYBOARD.SYS, KEYBRD2.SYS, ...
*/
static const char* ms_kb1[] = {
"be", "br", "cf", "cz", "dk", "fr", "gr", "hu", "it", "la",
"nl", "no", "pl", "po", "sf", "sg", "sl", "sp", "su", "sv",
"uk", "us", "yu" };
static const char* ms_kb2[] = {
"bg", "br", "cf", "cz", "gk", "gr", "hu", "is", "it", "no",
"pl", "ro", "ru", "sl", "su", "sv", "tr", "uk", "us", "yc",
"yu" };
static const char* ms_kb3[] = {
"be", "bl", "cz", "dk", "fr", "gr", "hu", "it", "nl", "pl",
"ru", "sf", "sg", "sl", "sp", "su", "sv", "uk", "ur", "us",
"yu" };
static const char* ms_kb4[] = {
"ar", "et", "gk", "he", "pl", "us" };
/*
* The following lists the keyboard code that are supported in each
* of the FreeDOS DOS KEYBOARD.SYS, KEYBRD2.SYS, ...
*/
static const char* fd_kb1[] = {
"be", "br", "cf", "co", "cz", "dk", "dv", "fr", "gr", "hu",
"it", "jp", "la", "lh", "nl", "no", "pl", "po", "rh", "sf",
"sg", "sk", "sp", "su", "sv", "uk", "us", "yu" };
static const char* fd_kb2[] = {
"bg", "ce", "gk", "is", "ro", "ru", "rx", "tr", "tt", "yc" };
static const char* fd_kb3[] = {
"az", "bl", "et", "fo", "hy", "il", "ka", "kk", "ky", "lt",
"lv", "mk", "mn", "mt", "ph", "sq", "tj", "tm", "ur", "uz",
"vi" };
static const char* fd_kb4[] = {
"ar", "bn", "bx", "fx", "ix", "kx", "ne", "ng", "px", "sx",
"ux" };
typedef struct {
const char* name;
ULONG default_cp;
} kb_default;
static kb_default kbdrv_data[] = {
{ "keyboard.sys", 437 },
{ "keybrd2.sys", 850 },
{ "keybrd3.sys", 850 },
{ "keybrd4.sys", 853 }
};
typedef struct {
size_t size;
const char** list;
} kb_list;
static kb_list ms_kb_list[] = {
{ ARRAYSIZE(ms_kb1), ms_kb1 },
{ ARRAYSIZE(ms_kb2), ms_kb2 },
{ ARRAYSIZE(ms_kb3), ms_kb3 },
{ ARRAYSIZE(ms_kb4), ms_kb4 }
};
static kb_list fd_kb_list[] = {
{ ARRAYSIZE(fd_kb1), fd_kb1 },
{ ARRAYSIZE(fd_kb2), fd_kb2 },
{ ARRAYSIZE(fd_kb3), fd_kb3 },
{ ARRAYSIZE(fd_kb4), fd_kb4 }
};
static int ms_get_kbdrv(const char* kb)
{
unsigned int i, j;
for (i = 0; i<ARRAYSIZE(ms_kb_list); i++) {
for (j = 0; j < ms_kb_list[i].size; j++) {
if (safe_strcmp(ms_kb_list[i].list[j], kb) == 0) {
return i;
}
}
}
return -1;
}
static int fd_get_kbdrv(const char* kb)
{
unsigned int i, j;
for (i = 0; i < ARRAYSIZE(fd_kb_list); i++) {
for (j = 0; j < fd_kb_list[i].size; j++) {
if (safe_strcmp(fd_kb_list[i].list[j], kb) == 0) {
return i;
}
}
}
return -1;
}
/*
* We display human readable descriptions of the locale in the menu
* As real estate might be limited, keep it short
*/
static const char* kb_hr_list[][2] = {
{"ar", "Arabic"}, // Left enabled, but doesn't seem to work in FreeDOS
{"bg", "Bulgarian"},
{"ch", "Chinese"},
{"cz", "Czech"},
{"dk", "Danish"},
{"gr", "German"},
{"sg", "Swiss-German"},
{"gk", "Greek"},
{"us", "US-English"},
{"uk", "UK-English"},
{"cf", "CA-French"},
{"dv", "US-Dvorak"},
{"lh", "US-Dvorak (LH)"},
{"rh", "US-Dvorak (RH)"},
{"sp", "Spanish"},
{"la", "Latin-American"},
{"su", "Finnish"},
{"fr", "French"},
{"be", "Belgian-French"},
{"sf", "Swiss-French"},
{"il", "Hebrew"},
{"hu", "Hungarian"},
{"is", "Icelandic"},
{"it", "Italian"},
{"jp", "Japanese"},
// {"ko", "Korean"}, // Unsupported by FreeDOS
{"nl", "Dutch"},
{"no", "Norwegian"},
{"pl", "Polish"},
{"br", "Brazilian"},
{"po", "Portuguese"},
{"ro", "Romanian"},
{"ru", "Russian"},
{"yu", "YU-Latin"},
{"yc", "YU-Cyrillic"},
{"sl", "Slovak"},
{"sq", "Albanian"},
{"sv", "Swedish"},
{"tr", "Turkish"},
{"ur", "Ukrainian"},
{"bl", "Belarusian"},
{"et", "Estonian"},
{"lv", "Latvian"},
{"lt", "Lithuanian"},
{"tj", "Tajik"},
// {"fa", "Persian"}; // Unsupported by FreeDOS
{"vi", "Vietnamese"},
{"hy", "Armenian"},
{"az", "Azeri"},
{"mk", "Macedonian"},
{"ka", "Georgian"},
{"fo", "Faeroese"},
{"mt", "Maltese"},
{"kk", "Kazakh"},
{"ky", "Kyrgyz"},
{"uz", "Uzbek"},
{"tm", "Turkmen"},
{"tt", "Tatar"},
};
static const char* kb_to_hr(const char* kb)
{
int i;
for (i = 0; i < ARRAYSIZE(kb_hr_list); i++) {
if (safe_strcmp(kb, kb_hr_list[i][0]) == 0) {
return kb_hr_list[i][1];
}
}
// Should never happen, so let's try to get some attention here
assert(i < ARRAYSIZE(kb_hr_list));
return NULL;
}
typedef struct {
ULONG cp;
const char* name;
} cp_list;
// From FreeDOS CPX pack as well as
// http://msdn.microsoft.com/en-us/library/dd317756.aspx
static cp_list cp_hr_list[] = {
{ 113, "Lat-Yugoslavian"},
{ 437, "US-English"},
{ 667, "Polish"},
{ 668, "Polish (Alt)"},
{ 708, "Arabic (708)"},
{ 709, "Arabic (709)"},
{ 710, "Arabic (710)"},
{ 720, "Arabic (DOS)"},
{ 737, "Greek (DOS)"},
{ 770, "Baltic"},
{ 771, "Cyr-Russian (KBL)"},
{ 772, "Cyr-Russian"},
{ 773, "Baltic Rim (Old)"},
{ 774, "Lithuanian"},
{ 775, "Baltic Rim"},
{ 777, "Acc-Lithuanian (Old)"},
{ 778, "Acc-Lithuanian"},
{ 790, "Mazovian-Polish"},
{ 808, "Cyr-Russian (Euro)"},
{ 848, "Cyr-Ukrainian (Euro)"},
{ 849, "Cyr-Belarusian (Euro)"},
{ 850, "Western-European"},
{ 851, "Greek"},
{ 852, "Central-European"},
{ 853, "Southern-European"},
{ 855, "Cyr-South-Slavic"},
{ 856, "Hebrew II"},
{ 857, "Turkish"},
{ 858, "Western-European (Euro)"},
{ 859, "Western-European (Alt)"},
{ 860, "Portuguese"},
{ 861, "Icelandic"},
{ 862, "Hebrew"},
{ 863, "Canadian-French"},
{ 864, "Arabic"},
{ 865, "Nordic"},
{ 866, "Cyr-Russian"},
{ 867, "Czech Kamenicky"},
{ 869, "Modern Greek"},
{ 872, "Cyr-South-Slavic (Euro)"},
{ 874, "Thai"},
{ 895, "Czech Kamenicky (Alt)"},
{ 899, "Armenian"},
{ 932, "Japanese"},
{ 936, "Chinese (Simplified)"},
{ 949, "Korean"},
{ 950, "Chinese (Traditional)"},
{ 991, "Mazovian-Polish (Zloty)"},
{ 1116, "Estonian"},
{ 1117, "Latvian"},
{ 1118, "Lithuanian"},
{ 1119, "Cyr-Russian (Alt)"},
{ 1125, "Cyr-Ukrainian"},
{ 1131, "Cyr-Belarusian"},
{ 1250, "Central European"},
{ 1251, "Cyrillic"},
{ 1252, "Western European"},
{ 1253, "Greek"},
{ 1254, "Turkish"},
{ 1255, "Hebrew"},
{ 1256, "Arabic"},
{ 1257, "Baltic"},
{ 1258, "Vietnamese"},
{ 1361, "Korean"},
{ 3012, "Cyr-Latvian"},
{ 3021, "Cyr-Bulgarian"},
{ 3845, "Hungarian"},
{ 3846, "Turkish"},
{ 3848, "Brazilian (ABICOMP)"},
{ 30000, "Saami"},
{ 30001, "Celtic"},
{ 30002, "Cyr-Tajik"},
{ 30003, "Latin American"},
{ 30004, "Greenlandic"},
{ 30005, "Nigerian"},
{ 30006, "Vietnamese"},
{ 30007, "Latin"},
{ 30008, "Cyr-Ossetian"},
{ 30009, "Romani"},
{ 30010, "Cyr-Moldovan"},
{ 30011, "Cyr-Chechen"},
{ 30012, "Cyr-Siberian"},
{ 30013, "Cyr-Turkic"},
{ 30014, "Cyr-Finno-Ugric"},
{ 30015, "Cyr-Khanty"},
{ 30016, "Cyr-Mansi"},
{ 30017, "Cyr-Northwestern"},
{ 30018, "Lat-Tatar"},
{ 30019, "Lat-Chechen"},
{ 30020, "Low-Saxon and Frisian"},
{ 30021, "Oceanian"},
{ 30022, "First Nations"},
{ 30023, "Southern African"},
{ 30024, "North & East African"},
{ 30025, "Western African"},
{ 30026, "Central African"},
{ 30027, "Beninese"},
{ 30028, "Nigerian (Alt)"},
{ 30029, "Mexican"},
{ 30030, "Mexican (Alt)"},
{ 30031, "Northern-European"},
{ 30032, "Nordic"},
{ 30033, "Crimean-Tatar (Hryvnia)"},
{ 30034, "Cherokee"},
{ 30039, "Cyr-Ukrainian (Hryvnia)"},
{ 30040, "Cyr-Russian (Hryvnia)"},
{ 58152, "Cyr-Kazakh (Euro)"},
{ 58210, "Cyr-Azeri"},
{ 58335, "Kashubian"},
{ 59234, "Cyr-Tatar"},
{ 59829, "Georgian"},
{ 60258, "Lat-Azeri"},
{ 60853, "Georgian (Alt)"},
{ 62306, "Cyr-Uzbek"},
{ 65001, "Unicode (UTF-8)" }
};
static const char* cp_to_hr(ULONG cp)
{
int i;
for (i = 0; i < ARRAYSIZE(cp_hr_list); i++) {
if (cp_hr_list[i].cp == cp) {
return cp_hr_list[i].name;
}
}
// Should never happen, so this oughta get some attention
assert(i < ARRAYSIZE(cp_hr_list));
return NULL;
}
// http://blogs.msdn.com/b/michkap/archive/2004/12/05/275231.aspx
static const char* get_kb(void)
{
unsigned int kbid;
char kbid_str[KL_NAMELENGTH];
int pass;
// Count on Microsoft to add convolution to a simple operation.
// We use GetKeyboardLayout() because it returns an HKL, which for instance
// doesn't tell us if the *LAYOUT* is Dvorak or something else. For that we
// need an KLID which GetKeyboardLayoutNameA() does return ...but only as a
// string of an hex value...
GetKeyboardLayoutNameA(kbid_str);
if (sscanf(kbid_str, "%x", &kbid) <= 0) {
uprintf("Could not scan keyboard layout name - defaulting to US");
kbid = 0x00000409;
}
uprintf("Windows KBID 0x%08x\n", kbid);
for (pass = 0; pass < 3; pass++) {
// Some of these return values are defined in
// HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout\DosKeybCodes
// Others are picked up in FreeDOS official keyboard layouts, v3.0
// Note: keyboard values are meant to start at 0x400. The cases below 0x400 are added
// to attempt to figure out a "best match" in case we couldn't find a supported keyboard
// by using the one most relevant to the language being spoken. Also we intentionally
// group keyboards that shouldn't be together
// Note: these cases are mostly organized first by (kbid & 0x3ff) and then by
// ascending order for same (kbid & 0x3ff)
switch(kbid) {
case 0x00000001:
case 0x00010401: // Arabic (102)
case 0x00020401: // Arabic (102) AZERTY
return "ar";
case 0x00000002:
case 0x00000402: // Bulgarian (Typewriter)
case 0x00010402: // Bulgarian (Latin)
case 0x00020402: // Bulgarian (Phonetic)
case 0x00030402: // Bulgarian
case 0x00040402: // Bulgarian (Phonetic Traditional)
return "bg";
case 0x00000004:
case 0x00000404: // Chinese (Traditional) - US Keyboard
case 0x00000804: // Chinese (Simplified) - US Keyboard
case 0x00000c04: // Chinese (Traditional, Hong Kong) - US Keyboard
case 0x00001004: // Chinese (Simplified, Singapore) - US Keyboard
case 0x00001404: // Chinese (Traditional, Macao) - US Keyboard
return "ch";
case 0x00000005:
case 0x00000405: // Czech
case 0x00010405: // Czech (QWERTY)
case 0x00020405: // Czech Programmers
return "cz";
case 0x00000006:
case 0x00000406: // Danish
return "dk";
case 0x00000007:
case 0x00000407: // German
case 0x00010407: // German (IBM)
return "gr";
case 0x00000807: // Swiss German
return "sg";
case 0x00000008:
case 0x00000408: // Greek
case 0x00010408: // Greek (220)
case 0x00020408: // Greek (319)
case 0x00030408: // Greek (220) Latin
case 0x00040408: // Greek (319) Latin
case 0x00050408: // Greek Latin
case 0x00060408: // Greek Polytonic
return "gk";
case 0x00000009:
case 0x00000409: // US
case 0x00020409: // United States-International
case 0x00050409: // US English Table for IBM Arabic 238_L
return "us";
case 0x00000809: // United Kingdom
case 0x00000452: // United Kingdom Extended (Welsh)
case 0x00001809: // Irish
case 0x00011809: // Gaelic
return "uk";
case 0x00000c0c: // Canadian French (Legacy)
case 0x00001009: // Canadian French
case 0x00011009: // Canadian Multilingual Standard
return "cf";
case 0x00010409: // United States-Dvorak
return "dv";
case 0x00030409: // United States-Dvorak for left hand
return "lh";
case 0x00040409: // United States-Dvorak for right hand
return "rh";
case 0x0000000a:
case 0x0000040a: // Spanish
case 0x0001040a: // Spanish Variation
return "sp";
case 0x0000080a: // Latin American
return "la";
case 0x0000000b:
case 0x0000040b: // Finnish
case 0x0001083b: // Finnish with Sami
return "su";
case 0x0000000c:
case 0x0000040c: // French
case 0x0000046e: // Luxembourgish
return "fr";
case 0x0000080c: // Belgian French
case 0x0001080c: // Belgian (Comma)
return "be";
case 0x0000100c: // Swiss French
return "sf";
case 0x0000000d:
case 0x0000040d: // Hebrew
return "il";
case 0x0000000e:
case 0x0000040e: // Hungarian
case 0x0001040e: // Hungarian 101-key
return "hu";
case 0x0000000f:
case 0x0000040f: // Icelandic
return "is";
case 0x00000010:
case 0x00000410: // Italian
case 0x00010410: // Italian (142)
return "it";
case 0x00000011:
case 0x00000411: // Japanese
return "jp";
// case 0x00000012:
// case 0x00000412: // Korean
// return "ko"; // NOT IMPLEMENTED IN FREEDOS?
case 0x00000013:
case 0x00000413: // Dutch
case 0x00000813: // Belgian (Period)
return "nl";
case 0x00000014:
case 0x00000414: // Norwegian
case 0x0000043b: // Norwegian with Sami
case 0x0001043b: // Sami Extended Norway
return "no";
case 0x00000015:
case 0x00010415: // Polish (214)
case 0x00000415: // Polish (Programmers)
return "pl";
case 0x00000016:
case 0x00000416: // Portuguese (Brazilian ABNT)
case 0x00010416: // Portuguese (Brazilian ABNT2)
return "br";
case 0x00000816: // Portuguese (Portugal)
return "po";
case 0x00000018:
case 0x00000418: // Romanian (Legacy)
case 0x00010418: // Romanian (Standard)
case 0x00020418: // Romanian (Programmers)
return "ro";
case 0x00000019:
case 0x00000419: // Russian
case 0x00010419: // Russian (Typewriter)
return "ru";
case 0x0000001a:
case 0x0000041a: // Croatian
case 0x0000081a: // Serbian (Latin)
case 0x00000024:
case 0x00000424: // Slovenian
return "yu";
case 0x00000c1a: // Serbian (Cyrillic)
case 0x0000201a: // Bosnian (Cyrillic)
return "yc";
case 0x0000001b:
case 0x0000041b: // Slovak
case 0x0001041b: // Slovak (QWERTY)
return "sl";
case 0x0000001c:
case 0x0000041c: // Albanian
return "sq";
case 0x0000001d:
case 0x0000041d: // Swedish
case 0x0000083b: // Swedish with Sami
return "sv";
case 0x0000001f:
case 0x0000041f: // Turkish Q
case 0x0001041f: // Turkish F
return "tr";
case 0x00000022:
case 0x00000422: // Ukrainian
case 0x00020422: // Ukrainian (Enhanced)
return "ur";
case 0x00000023:
case 0x00000423: // Belarusian
return "bl";
case 0x00000025:
case 0x00000425: // Estonian
return "et";
case 0x00000026:
case 0x00000426: // Latvian
case 0x00010426: // Latvian (QWERTY)
return "lv";
case 0x00000027:
case 0x00000427: // Lithuanian IBM
case 0x00010427: // Lithuanian
case 0x00020427: // Lithuanian Standard
return "lt";
case 0x00000028:
case 0x00000428: // Tajik
return "tj";
// case 0x00000029:
// case 0x00000429: // Persian
// return "fa"; // NOT IMPLEMENTED IN FREEDOS?
case 0x0000002a:
case 0x0000042a: // Vietnamese
return "vi";
case 0x0000002b:
case 0x0000042b: // Armenian Eastern
case 0x0001042b: // Armenian Western
return "hy";
case 0x0000002c:
case 0x0000042c: // Azeri Latin
case 0x0000082c: // Azeri Cyrillic
return "az";
case 0x0000002f:
case 0x0000042f: // Macedonian (FYROM)
case 0x0001042f: // Macedonian (FYROM) - Standard
return "mk";
case 0x00000037:
case 0x00000437: // Georgian
case 0x00010437: // Georgian (QWERTY)
case 0x00020437: // Georgian (Ergonomic)
return "ka";
case 0x00000038:
case 0x00000438: // Faeroese
return "fo";
case 0x0000003a:
case 0x0000043a: // Maltese 47-Key
case 0x0001043a: // Maltese 48-Key
return "mt";
case 0x0000003f:
case 0x0000043f: // Kazakh
return "kk";
case 0x00000040:
case 0x00000440: // Kyrgyz Cyrillic
return "ky";
case 0x00000043:
case 0x00000843: // Uzbek Cyrillic
return "uz";
case 0x00000042:
case 0x00000442: // Turkmen
return "tm";
case 0x00000044:
case 0x00000444: // Tatar
return "tt";
// Below are more Windows 7 listed keyboards that were left out
#if 0
case 0x0000041e: // Thai Kedmanee
case 0x0001041e: // Thai Pattachote
case 0x0002041e: // Thai Kedmanee (non-ShiftLock)
case 0x0003041e: // Thai Pattachote (non-ShiftLock)
case 0x00000420: // Urdu
case 0x0000042e: // Sorbian Standard (Legacy)
case 0x0001042e: // Sorbian Extended
case 0x0002042e: // Sorbian Standard
case 0x00000432: // Setswana
case 0x00000439: // Devanagari - INSCRIPT#
case 0x00010439: // Hindi Traditional
case 0x0002083b: // Sami Extended Finland-Sweden
case 0x00000445: // Bengali
case 0x00010445: // Bengali - INSCRIPT (Legacy)
case 0x00020445: // Bengali - INSCRIPT
case 0x00000446: // Punjabi
case 0x00000447: // Gujarati
case 0x00000448: // Oriya
case 0x00000449: // Tamil
case 0x0000044a: // Telugu
case 0x0000044b: // Kannada
case 0x0000044c: // Malayalam
case 0x0000044d: // Assamese - INSCRIPT
case 0x0000044e: // Marathi
case 0x00000450: // Mongolian Cyrillic
case 0x00000451: // Tibetan
case 0x00000850: // Mongolian (Mongolian Script)
case 0x0000085d: // Inuktitut - Latin
case 0x0001045d: // Inuktitut - Naqittaut
case 0x00000453: // Khmer
case 0x00000454: // Lao
case 0x0000045a: // Syriac
case 0x0001045a: // Syriac Phonetic
case 0x0000045b: // Sinhala
case 0x0001045b: // Sinhala - Wij 9
case 0x00000461: // Nepali
case 0x00000463: // Pashto (Afghanistan)
case 0x00000465: // Divehi Phonetic
case 0x00010465: // Divehi Typewriter
case 0x00000468: // Hausa
case 0x0000046a: // Yoruba
case 0x0000046c: // Sesotho sa Leboa
case 0x0000046d: // Bashkir
case 0x0000046f: // Greenlandic
case 0x00000470: // Igbo
case 0x00000480: // Uyghur (Legacy)
case 0x00010480: // Uyghur
case 0x00000481: // Maori
case 0x00000485: // Yakut
case 0x00000488: // Wolof
#endif
default:
if (pass == 0) {
// If we didn't get a match 1st time around, try to match
// the primary language of the keyboard
kbid = PRIMARYLANGID(kbid);
} else if (pass == 1) {
// If we still didn't get a match, use the system's primary language
kbid = PRIMARYLANGID(GetSystemDefaultLangID());
uprintf("Unable to match KBID, trying LangID 0x%04x", kbid);
}
break;
}
}
uprintf("Unable to match KBID and LangID - defaulting to US");
return "us";
}
/*
* From WinME DOS
*
* EGA.CPI:
* 0x01B5 437 (United States)
* 0x0352 850 (Latin 1)
* 0x0354 852 (Latin 2)
* 0x035C 860 (Portuguese)
* 0x035F 863 (French Canadian)
* 0x0361 865 (Nordic)
*
* EGA2.CPI:
* 0x0352 850 (Latin 1)
* 0x0354 852 (Latin 2)
* 0x0359 857 (Turkish)
* 0x035D 861 (Icelandic)
* 0x0365 869 (Greek)
* 0x02E1 737 (Greek II)
*
* EGA3.CPI:
* 0x01B5 437 (United States)
* 0x0307 775 (Baltic)
* 0x0352 850 (Latin 1)
* 0x0354 852 (Latin 2)
* 0x0357 855 (Cyrillic I)
* 0x0362 866 (Cyrillic II)
*/
// Pick the EGA to use according to the DOS target codepage (see above)
static const char* ms_get_ega(ULONG cp)
{
switch(cp) {
case 437: // United States
case 850: // Latin-1 (Western European)
case 852: // Latin-2 (Central European)
case 860: // Portuguese
case 863: // French Canadian
case 865: // Nordic
return "ega.cpi";
// case 850: // Latin-1 (Western European)
// case 852: // Latin-2 (Central European)
case 857: // Turkish
case 861: // Icelandic
case 869: // Greek
case 737: // Greek II
return "ega2.cpi";
// case 437: // United States
case 775: // Baltic
// case 850: // Latin-1 (Western European)
// case 852: // Latin-2 (Central European)
case 855: // Cyrillic I
case 866: // Cyrillic II
return "ega3.cpi";
default:
return NULL;
}
}
// Pick the EGA to use according to the DOS target codepage (from CPIDOS' Codepage.txt)
static const char* fd_get_ega(ULONG cp)
{
switch(cp) {
case 437: // United States
case 850: // Latin-1 (Western European)
case 852: // Latin-2 (Central European)
case 853: // Latin-3 (Southern European)
case 857: // Latin-5
case 858: // Latin-1 with Euro
return "ega.cpx";
case 775: // Latin-7 (Baltic Rim)
case 859: // Latin-9
case 1116: // Estonian
case 1117: // Latvian
case 1118: // Lithuanian
case 1119: // Cyrillic Russian and Lithuanian (*)
return "ega2.cpx";
case 771: // Cyrillic Russian and Lithuanian (KBL)
case 772: // Cyrillic Russian and Lithuanian
case 808: // Cyrillic Russian with Euro
case 855: // Cyrillic South Slavic
case 866: // Cyrillic Russian
case 872: // Cyrillic South Slavic with Euro
return "ega3.cpx";
case 848: // Cyrillic Ukrainian with Euro
case 849: // Cyrillic Belarusian with Euro
case 1125: // Cyrillic Ukrainian
case 1131: // Cyrillic Belarusian
case 3012: // Cyrillic Russian and Latvian ("RusLat")
case 30010: // Cyrillic Gagauz and Moldovan
return "ega4.cpx";
case 113: // Yugoslavian Latin
case 737: // Greek-2
case 851: // Greek (old codepage)
// case 852: // Latin-2
// case 858: // Multilingual Latin-1 with Euro
case 869: // Greek
return "ega5.cpx";
case 899: // Armenian
case 30008: // Cyrillic Abkhaz and Ossetian
case 58210: // Cyrillic Russian and Azeri
case 59829: // Georgian
case 60258: // Cyrillic Russian and Latin Azeri
case 60853: // Georgian with capital letters
return "ega6.cpx";
case 30011: // Cyrillic Russian Southern District
case 30013: // Cyrillic Volga District: // Turkic languages
case 30014: // Cyrillic Volga District: // Finno-ugric languages
case 30017: // Cyrillic Northwestern District
case 30018: // Cyrillic Russian and Latin Tatar
case 30019: // Cyrillic Russian and Latin Chechen
return "ega7.cpx";
case 770: // Baltic
case 773: // Latin-7 (old standard)
case 774: // Lithuanian
// case 775: // Latin-7
case 777: // Accented Lithuanian (old)
case 778: // Accented Lithuanian
return "ega8.cpx";
// case 858: // Latin-1 with Euro
case 860: // Portuguese
case 861: // Icelandic
case 863: // Canadian French
case 865: // Nordic
case 867: // Czech Kamenicky
return "ega9.cpx";
case 667: // Polish
case 668: // Polish (polish letters on cp852 codepoints)
case 790: // Polish Mazovia
// case 852: // Latin-2
case 991: // Polish Mazovia with Zloty sign
case 3845: // Hungarian
return "ega10.cpx";
// case 858: // Latin-1 with Euro
case 30000: // Saami
case 30001: // Celtic
case 30004: // Greenlandic
case 30007: // Latin
case 30009: // Romani
return "ega11.cpx";
// case 852: // Latin-2
// case 858: // Latin-1 with Euro
case 30003: // Latin American
case 30029: // Mexican
case 30030: // Mexican II
case 58335: // Kashubian
return "ega12";
// case 852: // Latin-2
case 895: // Czech Kamenicky
case 30002: // Cyrillic Tajik
case 58152: // Cyrillic Kazakh with Euro
case 59234: // Cyrillic Tatar
case 62306: // Cyrillic Uzbek
return "ega13.cpx";
case 30006: // Vietnamese
case 30012: // Cyrillic Russian Siberian and Far Eastern Districts
case 30015: // Cyrillic Khanty
case 30016: // Cyrillic Mansi
case 30020: // Low saxon and frisian
case 30021: // Oceania
return "ega14.cpx";
case 30023: // Southern Africa
case 30024: // Northern and Eastern Africa
case 30025: // Western Africa
case 30026: // Central Africa
case 30027: // Beninese
case 30028: // Nigerian II
return "ega15.cpx";
// case 858: // Latin-1 with Euro
case 3021: // Cyrillic MIK Bulgarian
case 30005: // Nigerian
case 30022: // Canadian First Nations
case 30031: // Latin-4 (Northern European)
case 30032: // Latin-6
return "ega16.cpx";
case 862: // Hebrew
case 864: // Arabic
case 30034: // Cherokee
case 30033: // Crimean Tatar with Hryvnia
case 30039: // Cyrillic Ukrainian with Hryvnia
case 30040: // Cyrillic Russian with Hryvnia
return "ega17.cpx";
case 856: // Hebrew II
case 3846: // Turkish
case 3848: // Brazilian ABICOMP
return "ega18.cpx";
default:
return NULL;
}
}
// Transliteration of the codepage (to add currency symbol, etc - FreeDOS only)
static ULONG fd_upgrade_cp(ULONG cp)
{
switch(cp) {
case 850: // Latin-1 (Western European)
return 858; // Latin-1 with Euro
default:
return cp;
}
}
// Don't bother about setting up the country or multiple codepages
BOOL SetDOSLocale(const char* path, BOOL bFreeDOS)
{
FILE* fd;
char filename[MAX_PATH];
ULONG cp;
UINT actual_cp;
const char *kb;
int kbdrv;
const char* egadrv;
// First handle the codepage
kb = get_kb();
// We have a keyboard ID, but that doesn't mean it's supported
kbdrv = bFreeDOS ? fd_get_kbdrv(kb) : ms_get_kbdrv(kb);
if (kbdrv < 0) {
uprintf("Keyboard id '%s' is not supported - falling back to 'us'", kb);
kb = "us";
kbdrv = bFreeDOS ? fd_get_kbdrv(kb) : ms_get_kbdrv(kb); // Always succeeds
}
assert(kbdrv >= 0);
uprintf("Will use DOS keyboard '%s' [%s]", kb, kb_to_hr(kb));
// Now get a codepage
cp = GetOEMCP();
if (cp == 65001) {
// GetOEMCP() may return UTF-8 for the codepage (65001),
// in which case we need to find the actual system OEM cp.
if (GetLocaleInfoA(GetUserDefaultUILanguage(), LOCALE_IDEFAULTCODEPAGE | LOCALE_RETURN_NUMBER,
(char*)&actual_cp, sizeof(actual_cp)))
cp = actual_cp;
}
egadrv = bFreeDOS ? fd_get_ega(cp) : ms_get_ega(cp);
if (egadrv == NULL) {
// We need to use the fallback CP from the keyboard we got above, as 437 is not always available
uprintf("Unable to find an EGA file with codepage %d [%s]", cp, cp_to_hr(cp));
cp = kbdrv_data[kbdrv].default_cp;
egadrv = bFreeDOS ? "ega.cpx" : "ega.cpi";
} else if (bFreeDOS) {
cp = fd_upgrade_cp(cp);
}
uprintf("Will use codepage %d [%s]", cp, cp_to_hr(cp));
if ((cp == 437) && (strcmp(kb, "us") == 0)) {
// Nothing much to do if US/US - just notify in autoexec.bat
static_strcpy(filename, path);
static_strcat(filename, "\\AUTOEXEC.BAT");
fd = fopen(filename, "w+");
if (fd == NULL) {
uprintf("Unable to create 'AUTOEXEC.BAT': %s", WindowsErrorString());
return FALSE;
}
fprintf(fd, "@echo off\n");
fprintf(fd, "set PATH=.;\\;\\LOCALE\n");
fprintf(fd, "echo Using %s keyboard with %s codepage [%d]\n", kb_to_hr("us"), cp_to_hr(437), 437);
fclose(fd);
uprintf("Successfully wrote 'AUTOEXEC.BAT'");
return TRUE;
}
// CONFIG.SYS
static_strcpy(filename, path);
static_strcat(filename, "\\CONFIG.SYS");
fd = fopen(filename, "w+");
if (fd == NULL) {
uprintf("Unable to create 'CONFIG.SYS': %s.", WindowsErrorString());
return FALSE;
}
if (bFreeDOS) {
fprintf(fd, "!MENUCOLOR=7,0\nMENU\nMENU FreeDOS Language Selection Menu\n");
fprintf(fd, "MENU \xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD"
"\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\nMENU\n");
} else {
fprintf(fd, "[MENU]\n");
}
fprintf(fd, "MENUDEFAULT=1,5\n");
// Menu item max: 70 characters
fprintf(fd, "%s1%c Use %s keyboard with %s codepage [%d]\n",
bFreeDOS?"MENU ":"MENUITEM=", bFreeDOS?')':',', kb_to_hr(kb), cp_to_hr(cp), (int)cp);
fprintf(fd, "%s2%c Use %s keyboard with %s codepage [%d]\n",
bFreeDOS?"MENU ":"MENUITEM=", bFreeDOS?')':',', kb_to_hr("us"), cp_to_hr(437), 437);
fprintf(fd, "%s", bFreeDOS?"MENU\n12?\n":"[1]\ndevice=\\locale\\display.sys con=(ega,,1)\n[2]\n");
fclose(fd);
uprintf("Successfully wrote 'CONFIG.SYS'");
// AUTOEXEC.BAT
static_strcpy(filename, path);
static_strcat(filename, "\\AUTOEXEC.BAT");
fd = fopen(filename, "w+");
if (fd == NULL) {
uprintf("Unable to create 'AUTOEXEC.BAT': %s", WindowsErrorString());
return FALSE;
}
fprintf(fd, "@echo off\n");
fprintf(fd, "set PATH=.;\\;\\LOCALE\n");
if (bFreeDOS)
fprintf(fd, "display con=(ega,,1)\n");
fprintf(fd, "GOTO %%CONFIG%%\n");
fprintf(fd, ":1\n");
fprintf(fd, "mode con codepage prepare=((%d) \\locale\\%s) > NUL\n", (int)cp, egadrv);
fprintf(fd, "mode con codepage select=%d > NUL\n", (int)cp);
fprintf(fd, "keyb %s,,\\locale\\%s\n", kb, kbdrv_data[kbdrv].name);
fprintf(fd, ":2\n");
fclose(fd);
uprintf("Successfully wrote 'AUTOEXEC.BAT'");
return TRUE;
}
| 30,136 |
C
|
.c
| 1,032 | 26.81686 | 100 | 0.656826 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
4,680 |
pki.c
|
pbatard_rufus/src/pki.c
|
/*
* Rufus: The Reliable USB Formatting Utility
* PKI functions (code signing, etc.)
* Copyright © 2015-2024 Pete Batard <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* Memory leaks detection - define _CRTDBG_MAP_ALLOC as preprocessor macro */
#ifdef _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#include <windows.h>
#include <stdio.h>
#include <wincrypt.h>
#include <wintrust.h>
#include <assert.h>
#include "rufus.h"
#include "resource.h"
#include "msapi_utf8.h"
#include "localization.h"
#define ENCODING (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING)
// MinGW doesn't seem to have this one
#if !defined(szOID_NESTED_SIGNATURE)
#define szOID_NESTED_SIGNATURE "1.3.6.1.4.1.311.2.4.1"
#endif
// Signatures names we accept. Must be the the exact name, including capitalization,
// that CertGetNameStringA(CERT_NAME_ATTR_TYPE, szOID_COMMON_NAME) returns.
const char* cert_name[3] = { "Akeo Consulting", "Akeo Systems", "Pete Batard" };
// For added security, we also validate the country code of the certificate recipient.
const char* cert_country = "IE";
typedef struct {
LPWSTR lpszProgramName;
LPWSTR lpszPublisherLink;
LPWSTR lpszMoreInfoLink;
} SPROG_PUBLISHERINFO, *PSPROG_PUBLISHERINFO;
// https://msdn.microsoft.com/en-us/library/ee442238.aspx
typedef struct {
BLOBHEADER BlobHeader;
RSAPUBKEY RsaHeader;
BYTE Modulus[256]; // 2048 bit modulus
} RSA_2048_PUBKEY;
// For PKCS7 WDAC Code Integrity processing
#define PE256_HASHSIZE 32
const GUID SKU_CODE_INTEGRITY_POLICY = { 0x976d12c8, 0xcb9f, 0x4730, { 0xbe, 0x52, 0x54, 0x60, 0x08, 0x43, 0x23, 0x8e} };
typedef struct {
WORD Nano;
WORD Micro;
WORD Minor;
WORD Major;
} CIVersion;
typedef struct {
DWORD PolicyFormatVersion;
GUID PolicyTypeGUID;
GUID PlatformGUID;
DWORD OptionFlags;
DWORD EKURuleEntryCount;
DWORD FileRuleEntryCount;
DWORD SignerRuleEntryCount;
DWORD SignerScenarioEntryCount;
CIVersion PolicyVersion;
DWORD HeaderLength;
} CIHeader;
typedef struct {
DWORD Type;
DWORD FileNameLength;
WCHAR FileName[0];
} CIFileRuleHeader;
typedef struct {
DWORD Unknown;
CIVersion Version;
DWORD HashLength;
BYTE Hash[0];
} CIFileRuleData;
enum {
CI_DENY = 0,
CI_ALLOW,
CI_FILE_ATTRIBUTES,
};
// The RSA public key modulus for the private key we use to sign the files on the server.
// NOTE 1: This openssl modulus must be *REVERSED* to be usable with Microsoft APIs
// NOTE 2: Also, this modulus is 2052 bits, and not 2048, because openssl adds an extra
// 0x00 at the beginning to force an integer sign. These extra 8 bits *MUST* be removed.
static uint8_t rsa_pubkey_modulus[] = {
/*
$ openssl genrsa -aes256 -out private.pem 2048
$ openssl rsa -in private.pem -pubout -out public.pem
$ openssl rsa -pubin -inform PEM -text -noout < public.pem
Public-Key: (2048 bit)
Modulus:
00:b6:40:7d:d1:98:7b:81:9e:be:23:0f:32:5d:55:
60:c6:bf:b4:41:bb:43:1b:f1:e1:e6:f9:2b:d6:dd:
11:50:e8:b9:3f:19:97:5e:a7:8b:4a:30:c6:76:58:
72:1c:ac:ff:a1:f8:96:6c:51:5d:13:11:e3:5b:11:
82:f5:9a:69:e4:28:97:0f:ca:1f:02:ea:1f:7d:dc:
f9:fc:79:2f:61:ff:8e:45:60:65:ba:37:9b:de:49:
05:6a:a8:fd:70:d0:0c:79:b6:d7:81:aa:54:c3:c6:
4a:87:a0:45:ee:ca:d5:d5:c5:c2:ac:86:42:b3:58:
27:d2:43:b9:37:f2:e6:75:66:17:53:d0:38:d0:c6:
57:c2:55:36:a2:43:87:ea:24:f0:96:ec:34:dd:79:
4d:80:54:9d:84:81:a7:cf:0c:a5:7c:d6:63:fa:7a:
66:30:a9:50:ee:f0:e5:f8:a2:2d:ac:fc:24:21:fe:
ef:e8:d3:6f:0e:27:b0:64:22:95:3e:6d:a6:66:97:
c6:98:c2:47:b3:98:69:4d:b1:b5:d3:6f:43:f5:d7:
a5:13:5e:8c:28:4f:62:4e:01:48:0a:63:89:e7:ca:
34:aa:7d:2f:bb:70:e0:31:bb:39:49:a3:d2:c9:2e:
a6:30:54:9a:5c:4d:58:17:d9:fc:3a:43:e6:8e:2a:
18:e9
Exponent: 65537 (0x10001)
*/
0x00, 0xb6, 0x40, 0x7d, 0xd1, 0x98, 0x7b, 0x81, 0x9e, 0xbe, 0x23, 0x0f, 0x32, 0x5d, 0x55,
0x60, 0xc6, 0xbf, 0xb4, 0x41, 0xbb, 0x43, 0x1b, 0xf1, 0xe1, 0xe6, 0xf9, 0x2b, 0xd6, 0xdd,
0x11, 0x50, 0xe8, 0xb9, 0x3f, 0x19, 0x97, 0x5e, 0xa7, 0x8b, 0x4a, 0x30, 0xc6, 0x76, 0x58,
0x72, 0x1c, 0xac, 0xff, 0xa1, 0xf8, 0x96, 0x6c, 0x51, 0x5d, 0x13, 0x11, 0xe3, 0x5b, 0x11,
0x82, 0xf5, 0x9a, 0x69, 0xe4, 0x28, 0x97, 0x0f, 0xca, 0x1f, 0x02, 0xea, 0x1f, 0x7d, 0xdc,
0xf9, 0xfc, 0x79, 0x2f, 0x61, 0xff, 0x8e, 0x45, 0x60, 0x65, 0xba, 0x37, 0x9b, 0xde, 0x49,
0x05, 0x6a, 0xa8, 0xfd, 0x70, 0xd0, 0x0c, 0x79, 0xb6, 0xd7, 0x81, 0xaa, 0x54, 0xc3, 0xc6,
0x4a, 0x87, 0xa0, 0x45, 0xee, 0xca, 0xd5, 0xd5, 0xc5, 0xc2, 0xac, 0x86, 0x42, 0xb3, 0x58,
0x27, 0xd2, 0x43, 0xb9, 0x37, 0xf2, 0xe6, 0x75, 0x66, 0x17, 0x53, 0xd0, 0x38, 0xd0, 0xc6,
0x57, 0xc2, 0x55, 0x36, 0xa2, 0x43, 0x87, 0xea, 0x24, 0xf0, 0x96, 0xec, 0x34, 0xdd, 0x79,
0x4d, 0x80, 0x54, 0x9d, 0x84, 0x81, 0xa7, 0xcf, 0x0c, 0xa5, 0x7c, 0xd6, 0x63, 0xfa, 0x7a,
0x66, 0x30, 0xa9, 0x50, 0xee, 0xf0, 0xe5, 0xf8, 0xa2, 0x2d, 0xac, 0xfc, 0x24, 0x21, 0xfe,
0xef, 0xe8, 0xd3, 0x6f, 0x0e, 0x27, 0xb0, 0x64, 0x22, 0x95, 0x3e, 0x6d, 0xa6, 0x66, 0x97,
0xc6, 0x98, 0xc2, 0x47, 0xb3, 0x98, 0x69, 0x4d, 0xb1, 0xb5, 0xd3, 0x6f, 0x43, 0xf5, 0xd7,
0xa5, 0x13, 0x5e, 0x8c, 0x28, 0x4f, 0x62, 0x4e, 0x01, 0x48, 0x0a, 0x63, 0x89, 0xe7, 0xca,
0x34, 0xaa, 0x7d, 0x2f, 0xbb, 0x70, 0xe0, 0x31, 0xbb, 0x39, 0x49, 0xa3, 0xd2, 0xc9, 0x2e,
0xa6, 0x30, 0x54, 0x9a, 0x5c, 0x4d, 0x58, 0x17, 0xd9, 0xfc, 0x3a, 0x43, 0xe6, 0x8e, 0x2a,
0x18, 0xe9
};
/*
* FormatMessage does not handle PKI errors
*/
const char* WinPKIErrorString(void)
{
static char error_string[64];
DWORD error_code = GetLastError();
if (((error_code >> 16) != 0x8009) && ((error_code >> 16) != 0x800B))
return WindowsErrorString();
switch (error_code) {
// See also https://docs.microsoft.com/en-gb/windows/desktop/com/com-error-codes-4
case NTE_BAD_UID:
return "Bad UID.";
case NTE_NO_KEY:
return "Key does not exist.";
case NTE_BAD_KEYSET:
return "Keyset does not exist.";
case NTE_BAD_ALGID:
return "Invalid algorithm specified.";
case NTE_BAD_VER:
return "Bad version of provider.";
case NTE_BAD_SIGNATURE:
return "Invalid Signature.";
case CRYPT_E_MSG_ERROR:
return "An error occurred while performing an operation on a cryptographic message.";
case CRYPT_E_UNKNOWN_ALGO:
return "Unknown cryptographic algorithm.";
case CRYPT_E_INVALID_MSG_TYPE:
return "Invalid cryptographic message type.";
case CRYPT_E_HASH_VALUE:
return "The hash value is not correct";
case CRYPT_E_ISSUER_SERIALNUMBER:
return "Invalid issuer and/or serial number.";
case CRYPT_E_BAD_LEN:
return "The length specified for the output data was insufficient.";
case CRYPT_E_BAD_ENCODE:
return "An error occurred during encode or decode operation.";
case CRYPT_E_FILE_ERROR:
return "An error occurred while reading or writing to a file.";
case CRYPT_E_NOT_FOUND:
return "Cannot find object or property.";
case CRYPT_E_EXISTS:
return "The object or property already exists.";
case CRYPT_E_NO_PROVIDER:
return "No provider was specified for the store or object.";
case CRYPT_E_DELETED_PREV:
return "The previous certificate or CRL context was deleted.";
case CRYPT_E_NO_MATCH:
return "Cannot find the requested object.";
case CRYPT_E_UNEXPECTED_MSG_TYPE:
case CRYPT_E_NO_KEY_PROPERTY:
case CRYPT_E_NO_DECRYPT_CERT:
return "Private key or certificate issue";
case CRYPT_E_BAD_MSG:
return "Not a cryptographic message.";
case CRYPT_E_NO_SIGNER:
return "The signed cryptographic message does not have a signer for the specified signer index.";
case CRYPT_E_REVOKED:
return "The certificate is revoked.";
case CRYPT_E_NO_REVOCATION_DLL:
case CRYPT_E_NO_REVOCATION_CHECK:
case CRYPT_E_REVOCATION_OFFLINE:
case CRYPT_E_NOT_IN_REVOCATION_DATABASE:
return "Cannot check certificate revocation.";
case CRYPT_E_INVALID_NUMERIC_STRING:
case CRYPT_E_INVALID_PRINTABLE_STRING:
case CRYPT_E_INVALID_IA5_STRING:
case CRYPT_E_INVALID_X500_STRING:
case CRYPT_E_NOT_CHAR_STRING:
return "Invalid string.";
case CRYPT_E_SECURITY_SETTINGS:
return "The cryptographic operation failed due to a local security option setting.";
case CRYPT_E_NO_VERIFY_USAGE_CHECK:
case CRYPT_E_VERIFY_USAGE_OFFLINE:
return "Cannot complete usage check.";
case CRYPT_E_NO_TRUSTED_SIGNER:
return "None of the signers of the cryptographic message or certificate trust list is trusted.";
case CERT_E_UNTRUSTEDROOT:
return "The root certificate is not trusted.";
case TRUST_E_SYSTEM_ERROR:
return "A system-level error occurred while verifying trust.";
case TRUST_E_NO_SIGNER_CERT:
return "The certificate for the signer of the message is invalid or not found.";
case TRUST_E_COUNTER_SIGNER:
return "One of the counter signatures was invalid.";
case TRUST_E_CERT_SIGNATURE:
return "The signature of the certificate cannot be verified.";
case TRUST_E_TIME_STAMP:
return "The timestamp could not be verified.";
case TRUST_E_BAD_DIGEST:
return "The file content has been altered.";
case TRUST_E_BASIC_CONSTRAINTS:
return "A certificate's basic constraint extension has not been observed.";
case TRUST_E_NOSIGNATURE:
return "Not digitally signed.";
case TRUST_E_EXPLICIT_DISTRUST:
return "One of the certificates used was marked as untrusted by the user.";
default:
static_sprintf(error_string, "Unknown PKI error 0x%08lX", error_code);
return error_string;
}
}
// Mostly from https://support.microsoft.com/en-us/kb/323809
char* GetSignatureName(const char* path, const char* country_code, BOOL bSilent)
{
static char szSubjectName[128];
char szCountry[3] = "__";
char *p = NULL, *mpath = NULL;
int i;
BOOL r;
HCERTSTORE hStore = NULL;
HCRYPTMSG hMsg = NULL;
PCCERT_CONTEXT pCertContext = NULL;
DWORD dwSize, dwEncoding, dwContentType, dwFormatType, dwSignerInfoSize = 0;
PCMSG_SIGNER_INFO pSignerInfo = NULL;
// TODO: Do we really need CertInfo? Or can we just reference pSignerInfo?
CERT_INFO CertInfo = { 0 };
SPROG_PUBLISHERINFO ProgPubInfo = { 0 };
wchar_t *szFileName;
// If the path is NULL, get the signature of the current runtime
if (path == NULL) {
szFileName = calloc(MAX_PATH, sizeof(wchar_t));
if (szFileName == NULL)
return NULL;
dwSize = GetModuleFileNameW(NULL, szFileName, MAX_PATH);
if ((dwSize == 0) || ((dwSize == MAX_PATH) && (GetLastError() == ERROR_INSUFFICIENT_BUFFER))) {
uprintf("PKI: Could not get module filename: %s", WinPKIErrorString());
goto out;
}
mpath = wchar_to_utf8(szFileName);
} else {
szFileName = utf8_to_wchar(path);
}
// Get message handle and store handle from the signed file.
for (i = 0; i < 5; i++) {
r = CryptQueryObject(CERT_QUERY_OBJECT_FILE, szFileName,
CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED, CERT_QUERY_FORMAT_FLAG_BINARY,
0, &dwEncoding, &dwContentType, &dwFormatType, &hStore, &hMsg, NULL);
if (r)
break;
if (i == 0)
uprintf("PKI: Failed to get signature for '%s': %s", (path==NULL)?mpath:path, WinPKIErrorString());
if (path == NULL)
break;
uprintf("PKI: Retrying...");
Sleep(2000);
}
if (!r)
goto out;
// Get signer information size.
r = CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, NULL, &dwSignerInfoSize);
if (!r) {
uprintf("PKI: Failed to get signer size: %s", WinPKIErrorString());
goto out;
}
// Allocate memory for signer information.
pSignerInfo = (PCMSG_SIGNER_INFO)calloc(dwSignerInfoSize, 1);
if (!pSignerInfo) {
uprintf("PKI: Could not allocate memory for signer information");
goto out;
}
// Get Signer Information.
r = CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, (PVOID)pSignerInfo, &dwSignerInfoSize);
if (!r) {
uprintf("PKI: Failed to get signer information: %s", WinPKIErrorString());
goto out;
}
// Search for the signer certificate in the temporary certificate store.
CertInfo.Issuer = pSignerInfo->Issuer;
CertInfo.SerialNumber = pSignerInfo->SerialNumber;
pCertContext = CertFindCertificateInStore(hStore, ENCODING, 0, CERT_FIND_SUBJECT_CERT, (PVOID)&CertInfo, NULL);
if (!pCertContext) {
uprintf("PKI: Failed to locate signer certificate in store: %s", WinPKIErrorString());
goto out;
}
// If a country code is provided, validate that the certificate we have is for the same country
if (country_code != NULL) {
dwSize = CertGetNameStringA(pCertContext, CERT_NAME_ATTR_TYPE, 0, szOID_COUNTRY_NAME,
szCountry, sizeof(szCountry));
if (dwSize < 2) {
uprintf("PKI: Failed to get Country Code");
goto out;
}
if (strcmpi(country_code, szCountry) != 0) {
uprintf("PKI: Unexpected Country Code (Found '%s', expected '%s')", szCountry, country_code);
goto out;
}
}
// Isolate the signing certificate subject name
dwSize = CertGetNameStringA(pCertContext, CERT_NAME_ATTR_TYPE, 0, szOID_COMMON_NAME,
szSubjectName, sizeof(szSubjectName));
if (dwSize <= 1) {
uprintf("PKI: Failed to get Subject Name");
goto out;
}
if (szCountry[0] == '_')
suprintf("Binary executable is signed by '%s'", szSubjectName);
else
suprintf("Binary executable is signed by '%s' (%s)", szSubjectName, szCountry);
p = szSubjectName;
out:
safe_free(mpath);
safe_free(szFileName);
safe_free(ProgPubInfo.lpszProgramName);
safe_free(ProgPubInfo.lpszPublisherLink);
safe_free(ProgPubInfo.lpszMoreInfoLink);
safe_free(pSignerInfo);
if (pCertContext != NULL)
CertFreeCertificateContext(pCertContext);
if (hStore != NULL)
CertCloseStore(hStore, 0);
if (hMsg != NULL)
CryptMsgClose(hMsg);
return p;
}
// Fills the certificate's name and thumbprint.
// Tries the issuer first, and if none is available, falls back to current cert.
// Returns 0 for unsigned, -1 on error, 1 for signer or 2 for issuer.
int GetIssuerCertificateInfo(uint8_t* cert, cert_info_t* info)
{
int ret = 0;
DWORD dwSize, dwEncoding, dwContentType, dwFormatType, dwSignerInfoSize = 0;
WIN_CERTIFICATE* pWinCert = (WIN_CERTIFICATE*)cert;
CRYPT_DATA_BLOB signedDataBlob;
HCERTSTORE hStore = NULL;
HCRYPTMSG hMsg = NULL;
PCMSG_SIGNER_INFO pSignerInfo = NULL;
PCCERT_CONTEXT pCertContext[2] = { NULL, NULL };
PCCERT_CHAIN_CONTEXT pChainContext = NULL;
CERT_CHAIN_PARA chainPara;
int CertIndex = 0;
if (info == NULL)
return -1;
if (pWinCert == NULL || pWinCert->dwLength == 0)
return 0;
// Get message handle and store handle from the signed file.
signedDataBlob.cbData = pWinCert->dwLength;
signedDataBlob.pbData = pWinCert->bCertificate;
if (!CryptQueryObject(CERT_QUERY_OBJECT_BLOB, &signedDataBlob,
CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED, CERT_QUERY_FORMAT_FLAG_BINARY,
0, &dwEncoding, &dwContentType, &dwFormatType, &hStore, &hMsg, NULL)) {
uprintf("PKI: Failed to get signature: %s", WinPKIErrorString());
goto out;
}
// Get signer information size.
if (!CryptMsgGetParam(hMsg, CMSG_SIGNER_CERT_INFO_PARAM, 0, NULL, &dwSignerInfoSize)) {
uprintf("PKI: Failed to get signer size: %s", WinPKIErrorString());
goto out;
}
// Allocate memory for signer information.
pSignerInfo = (PCMSG_SIGNER_INFO)calloc(dwSignerInfoSize, 1);
if (pSignerInfo == NULL) {
uprintf("PKI: Could not allocate memory for signer information");
goto out;
}
// Get Signer Information.
if (!CryptMsgGetParam(hMsg, CMSG_SIGNER_CERT_INFO_PARAM, 0, pSignerInfo, &dwSignerInfoSize)) {
uprintf("PKI: Failed to get signer info: %s", WinPKIErrorString());
goto out;
}
// Search for the signer certificate in the temporary certificate store.
pCertContext[0] = CertFindCertificateInStore(hStore, ENCODING, 0, CERT_FIND_SUBJECT_CERT, (PVOID)pSignerInfo, NULL);
if (pCertContext[0] == NULL) {
uprintf("PKI: Failed to locate signer certificate in store: %s", WinPKIErrorString());
goto out;
}
// Build a certificate chain to get the issuer (CA) certificate.
memset(&chainPara, 0, sizeof(chainPara));
chainPara.cbSize = sizeof(CERT_CHAIN_PARA);
if (!CertGetCertificateChain(NULL, pCertContext[0], NULL, hStore, &chainPara, 0, NULL, &pChainContext)) {
uprintf("PKI: Failed to build certificate chain. Error code: %s", WinPKIErrorString());
goto out;
}
// Try to get the issuer's certificate (second certificate in the chain) if available
if (pChainContext->cChain > 0 && pChainContext->rgpChain[0]->cElement > 1) {
pCertContext[1] = pChainContext->rgpChain[0]->rgpElement[1]->pCertContext;
CertIndex = 1;
}
// Isolate the signing certificate subject name
dwSize = CertGetNameStringA(pCertContext[CertIndex], CERT_NAME_ATTR_TYPE, 0, szOID_COMMON_NAME,
info->name, sizeof(info->name));
if (dwSize <= 1) {
uprintf("PKI: Failed to get Subject Name");
goto out;
}
dwSize = SHA1_HASHSIZE;
if (!CryptHashCertificate(0, CALG_SHA1, 0, pCertContext[CertIndex]->pbCertEncoded,
pCertContext[CertIndex]->cbCertEncoded, info->thumbprint, &dwSize)) {
uprintf("PKI: Failed to compute the thumbprint: %s", WinPKIErrorString());
goto out;
}
ret = CertIndex + 1;
out:
safe_free(pSignerInfo);
if (pCertContext[1] != NULL)
CertFreeCertificateContext(pCertContext[1]);
if (pCertContext[0] != NULL)
CertFreeCertificateContext(pCertContext[0]);
if (hStore != NULL)
CertCloseStore(hStore, 0);
if (hMsg != NULL)
CryptMsgClose(hMsg);
return ret;
}
// The timestamping authorities we use are RFC 3161 compliant
static uint64_t GetRFC3161TimeStamp(PCMSG_SIGNER_INFO pSignerInfo)
{
BOOL r, found = FALSE;
DWORD n, dwSize = 0;
PCRYPT_CONTENT_INFO pCounterSignerInfo = NULL;
uint64_t ts = 0ULL;
uint8_t *timestamp_token;
size_t timestamp_token_size;
char* timestamp_str;
size_t timestamp_str_size;
// Loop through unauthenticated attributes for szOID_RFC3161_counterSign OID
for (n = 0; n < pSignerInfo->UnauthAttrs.cAttr; n++) {
if (lstrcmpA(pSignerInfo->UnauthAttrs.rgAttr[n].pszObjId, szOID_RFC3161_counterSign) == 0) {
// Depending on how Microsoft implemented their timestamp checks, and the fact that we are dealing
// with UnauthAttrs, there's a possibility that an attacker may add a "fake" RFC 3161 countersigner
// to try to trick us into using their timestamp data. Detect that.
if (found) {
uprintf("PKI: Multiple RFC 3161 countersigners found. This could indicate something very nasty...");
return 0ULL;
}
found = TRUE;
// Read the countersigner message data
r = CryptDecodeObjectEx(PKCS_7_ASN_ENCODING, PKCS_CONTENT_INFO,
pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].pbData,
pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].cbData,
CRYPT_DECODE_ALLOC_FLAG, NULL, (PVOID)&pCounterSignerInfo, &dwSize);
if (!r) {
uprintf("PKI: Could not retrieve RFC 3161 countersigner data: %s", WinPKIErrorString());
continue;
}
// Get the RFC 3161 timestamp message
timestamp_token = get_data_from_asn1(pCounterSignerInfo->Content.pbData,
pCounterSignerInfo->Content.cbData, szOID_TIMESTAMP_TOKEN,
// 0x04 = "Octet String" ASN.1 tag
0x04, ×tamp_token_size);
if (timestamp_token) {
timestamp_str = get_data_from_asn1(timestamp_token, timestamp_token_size, NULL,
// 0x18 = "Generalized Time" ASN.1 tag
0x18, ×tamp_str_size);
if (timestamp_str) {
// As per RFC 3161 The syntax is: YYYYMMDDhhmmss[.s...]Z
if ((timestamp_str_size < 14) || (timestamp_str[timestamp_str_size - 1] != 'Z')) {
// Sanity checks
uprintf("PKI: Not an RFC 3161 timestamp");
DumpBufferHex(timestamp_str, timestamp_str_size);
} else {
ts = strtoull(timestamp_str, NULL, 10);
}
}
}
LocalFree(pCounterSignerInfo);
}
}
return ts;
}
// The following is used to get the RFP 3161 timestamp of a nested signature
static uint64_t GetNestedRFC3161TimeStamp(PCMSG_SIGNER_INFO pSignerInfo)
{
BOOL r, found = FALSE;
DWORD n, dwSize = 0;
PCRYPT_CONTENT_INFO pNestedSignature = NULL;
PCMSG_SIGNER_INFO pNestedSignerInfo = NULL;
HCRYPTMSG hMsg = NULL;
uint64_t ts = 0ULL;
// Loop through unauthenticated attributes for szOID_NESTED_SIGNATURE OID
for (n = 0; ; n++) {
if (pNestedSignature != NULL) {
LocalFree(pNestedSignature);
pNestedSignature = NULL;
}
if (hMsg != NULL) {
CryptMsgClose(hMsg);
hMsg = NULL;
}
safe_free(pNestedSignerInfo);
if (n >= pSignerInfo->UnauthAttrs.cAttr)
break;
if (lstrcmpA(pSignerInfo->UnauthAttrs.rgAttr[n].pszObjId, szOID_NESTED_SIGNATURE) == 0) {
if (found) {
uprintf("PKI: Multiple nested signatures found. This could indicate something very nasty...");
return 0ULL;
}
found = TRUE;
r = CryptDecodeObjectEx(PKCS_7_ASN_ENCODING, PKCS_CONTENT_INFO,
pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].pbData,
pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].cbData,
CRYPT_DECODE_ALLOC_FLAG, NULL, (PVOID)&pNestedSignature, &dwSize);
if (!r) {
uprintf("PKI: Could not retrieve nested signature data: %s", WinPKIErrorString());
continue;
}
hMsg = CryptMsgOpenToDecode(ENCODING, CMSG_DETACHED_FLAG, CMSG_SIGNED, (HCRYPTPROV)NULL, NULL, NULL);
if (hMsg == NULL) {
uprintf("PKI: Could not create nested signature message: %s", WinPKIErrorString());
continue;
}
r = CryptMsgUpdate(hMsg, pNestedSignature->Content.pbData, pNestedSignature->Content.cbData, TRUE);
if (!r) {
uprintf("PKI: Could not update message: %s", WinPKIErrorString());
continue;
}
// Get nested signer
r = CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, NULL, &dwSize);
if (!r) {
uprintf("PKI: Failed to get nested signer size: %s", WinPKIErrorString());
continue;
}
pNestedSignerInfo = (PCMSG_SIGNER_INFO)calloc(dwSize, 1);
if (!pNestedSignerInfo) {
uprintf("PKI: Could not allocate memory for nested signer");
continue;
}
r = CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, (PVOID)pNestedSignerInfo, &dwSize);
if (!r) {
uprintf("PKI: Failed to get nested signer information: %s", WinPKIErrorString());
continue;
}
ts = GetRFC3161TimeStamp(pNestedSignerInfo);
}
}
return ts;
}
// Return the signature timestamp (as a YYYYMMDDHHMMSS value) or 0 on error
uint64_t GetSignatureTimeStamp(const char* path)
{
char *mpath = NULL;
BOOL r;
HMODULE hm;
HCERTSTORE hStore = NULL;
HCRYPTMSG hMsg = NULL;
DWORD dwSize, dwEncoding, dwContentType, dwFormatType, dwSignerInfoSize = 0;
PCMSG_SIGNER_INFO pSignerInfo = NULL;
wchar_t *szFileName;
uint64_t timestamp = 0ULL, nested_timestamp;
// If the path is NULL, get the signature of the current runtime
if (path == NULL) {
szFileName = calloc(MAX_PATH, sizeof(wchar_t));
if (szFileName == NULL)
goto out;
hm = GetModuleHandle(NULL);
if (hm == NULL) {
uprintf("PKI: Could not get current executable handle: %s", WinPKIErrorString());
goto out;
}
dwSize = GetModuleFileNameW(hm, szFileName, MAX_PATH);
if ((dwSize == 0) || ((dwSize == MAX_PATH) && (GetLastError() == ERROR_INSUFFICIENT_BUFFER))) {
uprintf("PKI: Could not get module filename: %s", WinPKIErrorString());
goto out;
}
mpath = wchar_to_utf8(szFileName);
} else {
szFileName = utf8_to_wchar(path);
}
// Get message handle and store handle from the signed file.
r = CryptQueryObject(CERT_QUERY_OBJECT_FILE, szFileName,
CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED, CERT_QUERY_FORMAT_FLAG_BINARY,
0, &dwEncoding, &dwContentType, &dwFormatType, &hStore, &hMsg, NULL);
if (!r) {
uprintf("PKI: Failed to get signature for '%s': %s", (path==NULL)?mpath:path, WinPKIErrorString());
goto out;
}
// Get signer information size.
r = CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, NULL, &dwSignerInfoSize);
if (!r) {
uprintf("PKI: Failed to get signer size: %s", WinPKIErrorString());
goto out;
}
// Allocate memory for signer information.
pSignerInfo = (PCMSG_SIGNER_INFO)calloc(dwSignerInfoSize, 1);
if (!pSignerInfo) {
uprintf("PKI: Could not allocate memory for signer information");
goto out;
}
// Get Signer Information.
r = CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, (PVOID)pSignerInfo, &dwSignerInfoSize);
if (!r) {
uprintf("PKI: Failed to get signer information: %s", WinPKIErrorString());
goto out;
}
// Get the RFC 3161 timestamp
timestamp = GetRFC3161TimeStamp(pSignerInfo);
if (timestamp)
uprintf("Note: '%s' has timestamp %s", (path==NULL)?mpath:path, TimestampToHumanReadable(timestamp));
// Because we were using both SHA-1 and SHA-256 signatures during the SHA-256 transition, we were
// in the very specific situation where Windows could say that our executable passed Authenticode
// validation even if the SHA-1 signature or timestamps had been altered.
// This means that, unless we also check the nested signature timestamp, an attacker could alter
// the most vulnerable signature (which may also be the one used for chronology validation) and
// trick us into using an invalid timestamp value. To prevent this, we validate that, if we have
// both a regular and nested timestamp, they are within 60 seconds of each other.
// Even as we are no longer dual signing with two versions of SHA, we keep the code in case a
// major SHA-256 vulnerability is found and we have to go through a dual SHA again.
nested_timestamp = GetNestedRFC3161TimeStamp(pSignerInfo);
if (nested_timestamp)
uprintf("Note: '%s' has nested timestamp %s", (path==NULL)?mpath:path, TimestampToHumanReadable(nested_timestamp));
if ((timestamp != 0ULL) && (nested_timestamp != 0ULL)) {
if (_abs64(nested_timestamp - timestamp) > 100) {
uprintf("PKI: Signature timestamp and nested timestamp differ by more than a minute. "
"This could indicate something very nasty...", timestamp, nested_timestamp);
timestamp = 0ULL;
}
}
out:
safe_free(mpath);
safe_free(szFileName);
safe_free(pSignerInfo);
if (hStore != NULL)
CertCloseStore(hStore, 0);
if (hMsg != NULL)
CryptMsgClose(hMsg);
return timestamp;
}
// From https://msdn.microsoft.com/en-us/library/windows/desktop/aa382384.aspx
LONG ValidateSignature(HWND hDlg, const char* path)
{
LONG r = TRUST_E_SYSTEM_ERROR;
WINTRUST_DATA trust_data = { 0 };
WINTRUST_FILE_INFO trust_file = { 0 };
GUID guid_generic_verify = // WINTRUST_ACTION_GENERIC_VERIFY_V2
{ 0xaac56b, 0xcd44, 0x11d0,{ 0x8c, 0xc2, 0x0, 0xc0, 0x4f, 0xc2, 0x95, 0xee } };
char *signature_name;
size_t i;
uint64_t current_ts, update_ts;
// Check the signature name. Make it specific enough (i.e. don't simply check for "Akeo")
// so that, besides hacking our server, it'll place an extra hurdle on any malicious entity
// into also fooling a C.A. to issue a certificate that passes our test.
signature_name = GetSignatureName(path, cert_country, (hDlg == INVALID_HANDLE_VALUE));
if (signature_name == NULL) {
uprintf("PKI: Could not get signature name");
if (hDlg != INVALID_HANDLE_VALUE)
MessageBoxExU(hDlg, lmprintf(MSG_284), lmprintf(MSG_283), MB_OK | MB_ICONERROR | MB_IS_RTL, selected_langid);
return TRUST_E_NOSIGNATURE;
}
for (i = 0; i < ARRAYSIZE(cert_name); i++) {
if (strcmp(signature_name, cert_name[i]) == 0)
break;
}
if (i >= ARRAYSIZE(cert_name)) {
uprintf("PKI: Signature '%s' is unexpected...", signature_name);
if ((hDlg == INVALID_HANDLE_VALUE) || (MessageBoxExU(hDlg,
lmprintf(MSG_285, signature_name), lmprintf(MSG_283),
MB_YESNO | MB_ICONWARNING | MB_IS_RTL, selected_langid) != IDYES))
return TRUST_E_EXPLICIT_DISTRUST;
}
trust_file.cbStruct = sizeof(trust_file);
trust_file.pcwszFilePath = utf8_to_wchar(path);
if (trust_file.pcwszFilePath == NULL) {
uprintf("PKI: Unable to convert '%s' to UTF16", path);
return RUFUS_ERROR(ERROR_NOT_ENOUGH_MEMORY);
}
trust_data.cbStruct = sizeof(trust_data);
// NB: WTD_UI_ALL can result in ERROR_SUCCESS even if the signature validation fails,
// because it still prompts the user to run untrusted software, even after explicitly
// notifying them that the signature invalid (and of course Microsoft had to make
// that UI prompt a bit too similar to the other benign prompt you get when running
// trusted software, which, as per cert.org's assessment, may confuse non-security
// conscious-users who decide to gloss over these kind of notifications).
trust_data.dwUIChoice = WTD_UI_NONE;
// We just downloaded from the Internet, so we should be able to check revocation
trust_data.fdwRevocationChecks = WTD_REVOKE_WHOLECHAIN;
// 0x400 = WTD_MOTW for Windows 8.1 or later
trust_data.dwProvFlags = WTD_REVOCATION_CHECK_CHAIN | 0x400;
trust_data.dwUnionChoice = WTD_CHOICE_FILE;
trust_data.pFile = &trust_file;
// NB: Calling this API will create DLL sideloading issues through 'msasn1.dll'.
// So make sure you delay-load 'wintrust.dll' in your application.
r = WinVerifyTrustEx(INVALID_HANDLE_VALUE, &guid_generic_verify, &trust_data);
safe_free(trust_file.pcwszFilePath);
switch (r) {
case ERROR_SUCCESS:
// hDlg = INVALID_HANDLE_VALUE is used when validating the Fido PS1 script
if (hDlg == INVALID_HANDLE_VALUE)
break;
// Verify that the timestamp of the downloaded update is in the future of our current one.
// This is done to prevent the use of an officially signed, but older binary, as potential attack vector.
current_ts = GetSignatureTimeStamp(NULL);
if (current_ts == 0ULL) {
uprintf("PKI: Cannot retrieve the current binary's timestamp - Aborting update");
r = TRUST_E_TIME_STAMP;
} else {
update_ts = GetSignatureTimeStamp(path);
if (update_ts < current_ts) {
uprintf("PKI: Update timestamp (%" PRIi64 ") is younger than ours (%" PRIi64 ") - Aborting update", update_ts, current_ts);
r = TRUST_E_TIME_STAMP;
}
}
if ((r != ERROR_SUCCESS) && (force_update < 2))
MessageBoxExU(hDlg, lmprintf(MSG_300), lmprintf(MSG_299), MB_OK | MB_ICONERROR | MB_IS_RTL, selected_langid);
break;
case TRUST_E_NOSIGNATURE:
// Should already have been reported, but since we have a custom message for it...
uprintf("PKI: File does not appear to be signed: %s", WinPKIErrorString());
if (hDlg != INVALID_HANDLE_VALUE)
MessageBoxExU(hDlg, lmprintf(MSG_284), lmprintf(MSG_283), MB_OK | MB_ICONERROR | MB_IS_RTL, selected_langid);
break;
default:
uprintf("PKI: Failed to validate signature: %s", WinPKIErrorString());
if (hDlg != INVALID_HANDLE_VALUE)
MessageBoxExU(hDlg, lmprintf(MSG_240), lmprintf(MSG_283), MB_OK | MB_ICONERROR | MB_IS_RTL, selected_langid);
break;
}
return r;
}
// Why-oh-why am I the only one on github doing this openssl vs MS signature validation?!?
// For once, I'd like to find code samples from *OTHER PEOPLE* who went through this ordeal first...
BOOL ValidateOpensslSignature(BYTE* pbBuffer, DWORD dwBufferLen, BYTE* pbSignature, DWORD dwSigLen)
{
HCRYPTPROV hProv = 0;
HCRYPTHASH hHash = 0;
HCRYPTKEY hPubKey;
// We could load and convert an openssl PEM, but since we know what we need...
RSA_2048_PUBKEY pbMyPubKey = {
{ PUBLICKEYBLOB, CUR_BLOB_VERSION, 0, CALG_RSA_KEYX },
// $ openssl genrsa -aes256 -out private.pem 2048
// Generating RSA private key, 2048 bit long modulus
// e is 65537 (0x010001)
// => 0x010001 below. Also 0x31415352 = "RSA1"
{ 0x31415352, sizeof(pbMyPubKey.Modulus) * 8, 0x010001 },
{ 0 } // Modulus is initialized below
};
USHORT dwMyPubKeyLen = sizeof(pbMyPubKey);
BOOL r;
BYTE t;
int i, j;
// Get a handle to the default PROV_RSA_AES provider (AES so we get SHA-256 support).
// 2 passes in case we need to create a new container.
r = CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_NEWKEYSET | CRYPT_VERIFYCONTEXT);
if (!r) {
uprintf("PKI: Could not create the default key container: %s", WinPKIErrorString());
goto out;
}
// Reverse the modulus bytes from openssl (and also remove the extra unwanted 0x00)
assert(sizeof(rsa_pubkey_modulus) >= sizeof(pbMyPubKey.Modulus));
for (i = 0; i < sizeof(pbMyPubKey.Modulus); i++)
pbMyPubKey.Modulus[i] = rsa_pubkey_modulus[sizeof(rsa_pubkey_modulus) -1 - i];
// Import our RSA public key so that the MS API can use it
r = CryptImportKey(hProv, (BYTE*)&pbMyPubKey.BlobHeader, dwMyPubKeyLen, 0, 0, &hPubKey);
if (!r) {
uprintf("PKI: Could not import public key: %s", WinPKIErrorString());
goto out;
}
// Create the hash object.
r = CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash);
if (!r) {
uprintf("PKI: Could not create empty hash: %s", WinPKIErrorString());
goto out;
}
// Compute the cryptographic hash of the buffer.
r = CryptHashData(hHash, pbBuffer, dwBufferLen, 0);
if (!r) {
uprintf("PKI: Could not hash data: %s", WinPKIErrorString());
goto out;
}
// Reverse the signature bytes
for (i = 0, j = dwSigLen - 1; i < j; i++, j--) {
t = pbSignature[i];
pbSignature[i] = pbSignature[j];
pbSignature[j] = t;
}
// Now that we have all of the public key, hash and signature data in a
// format that Microsoft can handle, we can call CryptVerifySignature().
r = CryptVerifySignature(hHash, pbSignature, dwSigLen, hPubKey, NULL, 0);
if (!r) {
// If the signature is invalid, clear the buffer so that
// we don't keep potentially nasty stuff in memory.
memset(pbBuffer, 0, dwBufferLen);
uprintf("Signature validation failed: %s", WinPKIErrorString());
}
out:
if (hHash)
CryptDestroyHash(hHash);
if (hProv)
CryptReleaseContext(hProv, 0);
return r;
}
// The following SkuSiPolicy.p7b parsing code is derived from:
// https://gist.github.com/mattifestation/92e545bf1ee5b68eeb71d254cec2f78e
// by Matthew Graeber, with contributions by James Forshaw.
BOOL ParseSKUSiPolicy(void)
{
char path[MAX_PATH];
wchar_t* wpath = NULL;
BOOL r = FALSE;
DWORD i, dwEncoding, dwContentType, dwFormatType;
DWORD dwPolicySize = 0, dwBaseIndex = 0, dwSizeCount;
HCRYPTMSG hMsg = NULL;
CRYPT_DATA_BLOB pkcsData = { 0 };
DWORD* pdwEkuRules;
BYTE* pbRule;
CIHeader* Header;
CIFileRuleHeader* FileRuleHeader;
CIFileRuleData* FileRuleData;
pe256ssp_size = 0;
safe_free(pe256ssp);
// Must use sysnative for WOW
static_sprintf(path, "%s\\SecureBootUpdates\\SKUSiPolicy.p7b", sysnative_dir);
wpath = utf8_to_wchar(path);
if (wpath == NULL)
goto out;
r = CryptQueryObject(CERT_QUERY_OBJECT_FILE, wpath, CERT_QUERY_CONTENT_FLAG_ALL,
CERT_QUERY_FORMAT_FLAG_ALL, 0, &dwEncoding, &dwContentType, &dwFormatType, NULL,
&hMsg, NULL);
if (!r || dwContentType != CERT_QUERY_CONTENT_PKCS7_SIGNED)
goto out;
r = CryptMsgGetParam(hMsg, CMSG_CONTENT_PARAM, 0, NULL, &pkcsData.cbData);
if (!r || pkcsData.cbData == 0) {
uprintf("ParseSKUSiPolicy: Failed to retreive CMSG_CONTENT_PARAM size: %s", WindowsErrorString());
goto out;
}
pkcsData.pbData = malloc(pkcsData.cbData);
if (pkcsData.pbData == NULL)
goto out;
r = CryptMsgGetParam(hMsg, CMSG_CONTENT_PARAM, 0, pkcsData.pbData, &pkcsData.cbData);
if (!r) {
uprintf("ParseSKUSiPolicy: Failed to retreive CMSG_CONTENT_PARAM: %s", WindowsErrorString());
goto out;
}
// Now process the actual Security Policy content
if (pkcsData.pbData[0] == 4) {
dwPolicySize = pkcsData.pbData[1];
dwBaseIndex = 2;
if ((dwPolicySize & 0x80) == 0x80) {
dwSizeCount = dwPolicySize & 0x7F;
dwBaseIndex += dwSizeCount;
dwPolicySize = 0;
for (i = 0; i < dwSizeCount; i++) {
dwPolicySize = dwPolicySize << 8;
dwPolicySize = dwPolicySize | pkcsData.pbData[2 + i];
}
}
}
// Sanity checks
Header = (CIHeader*)&pkcsData.pbData[dwBaseIndex];
if (Header->HeaderLength + sizeof(uint32_t) != sizeof(CIHeader)) {
uprintf("ParseSKUSiPolicy: Unexpected Code Integrity Header size (0x%02x)", Header->HeaderLength);
goto out;
}
if (!CompareGUID(&Header->PolicyTypeGUID, &SKU_CODE_INTEGRITY_POLICY)) {
uprintf("ParseSKUSiPolicy: Unexpected Policy Type GUID %s", GuidToString(&Header->PolicyTypeGUID, TRUE));
goto out;
}
// Skip the EKU Rules
pdwEkuRules = (DWORD*) &pkcsData.pbData[dwBaseIndex + sizeof(CIHeader)];
for (i = 0; i < Header->EKURuleEntryCount; i++)
pdwEkuRules = &pdwEkuRules[(*pdwEkuRules + (2 * sizeof(DWORD) - 1)) / sizeof(DWORD)];
// Process the Files Rules
pbRule = (BYTE*)pdwEkuRules;
pe256ssp = malloc(Header->FileRuleEntryCount * PE256_HASHSIZE);
if (pe256ssp == NULL)
goto out;
for (i = 0; i < Header->FileRuleEntryCount; i++) {
FileRuleHeader = (CIFileRuleHeader*)pbRule;
pbRule = &pbRule[sizeof(CIFileRuleHeader)];
if (FileRuleHeader->FileNameLength != 0) {
// uprintf("%S", FileRuleHeader->FileName);
pbRule = &pbRule[((FileRuleHeader->FileNameLength + sizeof(DWORD) - 1) / sizeof(DWORD)) * sizeof(DWORD)];
}
FileRuleData = (CIFileRuleData*)pbRule;
if (FileRuleData->HashLength > 0x80) {
uprintf("ParseSKUSiPolicy: Unexpected hash length for entry %d (0x%02x)", i, FileRuleData->HashLength);
// We're probably screwed, so bail out
break;
}
// We are only interested in 'DENY' type with PE256 hashes
if (FileRuleHeader->Type == CI_DENY && FileRuleData->HashLength == PE256_HASHSIZE) {
// Microsoft has the bad habit of duplicating entries - only add a hash if it's different from previous entry
if ((pe256ssp_size == 0) ||
(memcmp(&pe256ssp[(pe256ssp_size - 1) * PE256_HASHSIZE], FileRuleData->Hash, PE256_HASHSIZE) != 0)) {
memcpy(&pe256ssp[pe256ssp_size * PE256_HASHSIZE], FileRuleData->Hash, PE256_HASHSIZE);
pe256ssp_size++;
}
}
pbRule = &pbRule[sizeof(CIFileRuleData) + ((FileRuleData->HashLength + sizeof(DWORD) - 1) / sizeof(DWORD)) * sizeof(DWORD)];
}
r = TRUE;
out:
if (hMsg != NULL)
CryptMsgClose(hMsg);
free(pkcsData.pbData);
free(wpath);
return r;
}
| 37,832 |
C
|
.c
| 927 | 38.179072 | 127 | 0.725253 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
4,683 |
resource.h
|
pbatard_rufus/src/resource.h
|
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by rufus.rc
//
#define IDD_DIALOG 101
#define IDD_ABOUTBOX 102
#define IDD_NOTIFICATION 103
#define IDD_SELECTION 104
#define IDD_LICENSE 105
#define IDD_LOG 106
#define IDD_UPDATE_POLICY 107
#define IDD_NEW_VERSION 108
#define IDD_HASH 109
#define IDD_LIST 110
#define IDI_ICON 120
#define IDI_LANG_16 121
#define IDI_INFO_16 122
#define IDI_SETTINGS_16 123
#define IDI_LOG_16 124
#define IDI_SAVE_16 125
#define IDI_HASH_16 126
#define IDI_LANG_24 131
#define IDI_INFO_24 132
#define IDI_SETTINGS_24 133
#define IDI_LOG_24 134
#define IDI_SAVE_24 135
#define IDI_HASH_24 136
#define IDI_LANG_32 141
#define IDI_INFO_32 142
#define IDI_SETTINGS_32 143
#define IDI_LOG_32 144
#define IDI_SAVE_32 145
#define IDI_HASH_32 146
#define IDR_FD_COMMAND_COM 300
#define IDR_FD_KERNEL_SYS 301
#define IDR_FD_DISPLAY_EXE 302
#define IDR_FD_KEYB_EXE 303
#define IDR_FD_MODE_COM 304
#define IDR_FD_KB1_SYS 305
#define IDR_FD_KB2_SYS 306
#define IDR_FD_KB3_SYS 307
#define IDR_FD_KB4_SYS 308
#define IDR_FD_EGA1_CPX 309
#define IDR_FD_EGA2_CPX 310
#define IDR_FD_EGA3_CPX 311
#define IDR_FD_EGA4_CPX 312
#define IDR_FD_EGA5_CPX 313
#define IDR_FD_EGA6_CPX 314
#define IDR_FD_EGA7_CPX 315
#define IDR_FD_EGA8_CPX 316
#define IDR_FD_EGA9_CPX 317
#define IDR_FD_EGA10_CPX 318
#define IDR_FD_EGA11_CPX 319
#define IDR_FD_EGA12_CPX 320
#define IDR_FD_EGA13_CPX 321
#define IDR_FD_EGA14_CPX 322
#define IDR_FD_EGA15_CPX 323
#define IDR_FD_EGA16_CPX 324
#define IDR_FD_EGA17_CPX 325
#define IDR_FD_EGA18_CPX 326
#define IDR_SL_LDLINUX_V4_BSS 400
#define IDR_SL_LDLINUX_V4_SYS 401
#define IDR_SL_LDLINUX_V6_BSS 402
#define IDR_SL_LDLINUX_V6_SYS 403
#define IDR_SL_MBOOT_C32 404
#define IDR_GR_GRUB_GRLDR_MBR 450
#define IDR_GR_GRUB2_CORE_IMG 451
#define IDR_SBR_MSG 452
#define IDR_LC_RUFUS_LOC 500
#define IDR_XT_HOGGER 501
#define IDR_UEFI_NTFS 502
#define IDR_SETUP_X64 503
#define IDR_SETUP_ARM64 504
// The following should match the ArchType array values + 600
#define IDR_MD5_BOOT 600
#define IDR_MD5_BOOTIA32 601
#define IDR_MD5_BOOTX64 602
#define IDR_MD5_BOOTARM 603
#define IDR_MD5_BOOTAA64 604
#define IDR_MD5_BOOTRISCV64 607
#define IDM_SELECT 901
#define IDM_DOWNLOAD 902
#define IDC_DEVICE 1001
#define IDC_FILE_SYSTEM 1002
#define IDC_START 1003
#define IDC_PARTITION_TYPE 1004
#define IDC_CLUSTER_SIZE 1005
#define IDC_STATUS 1006
#define IDC_LABEL 1007
#define IDC_QUICK_FORMAT 1008
#define IDC_BAD_BLOCKS 1009
#define IDC_PROGRESS 1010
#define IDC_BOOT_SELECTION 1011
#define IDC_NB_PASSES 1012
#define IDC_TEST 1013
#define IDC_SELECT 1014
#define IDC_EXTENDED_LABEL 1015
#define IDC_TARGET_SYSTEM 1017
#define IDC_PERSISTENCE_SIZE 1018
#define IDC_PERSISTENCE_UNITS 1019
#define IDC_OLD_BIOS_FIXES 1020
#define IDC_UEFI_MEDIA_VALIDATION 1021
#define IDC_LIST_USB_HDD 1022
#define IDC_STATUS_TOOLBAR 1023
#define IDC_SAVE 1024
#define IDC_HASH 1025
#define IDC_IMAGE_OPTION 1026
#define IDC_PERSISTENCE_SLIDER 1027
#define IDC_ADVANCED_DRIVE_PROPERTIES 1028
#define IDC_ADVANCED_FORMAT_OPTIONS 1029
#define IDC_ABOUT_LICENSE 1030
#define IDC_ABOUT_ICON 1031
#define IDC_ABOUT_COPYRIGHTS 1032
#define IDC_ABOUT_BLURB 1033
#define IDC_LICENSE_TEXT 1034
#define IDC_NOTIFICATION_ICON 1040
#define IDC_NOTIFICATION_TEXT 1041
#define IDC_NOTIFICATION_LINE 1042
#define IDC_ADVANCED_DEVICE_TOOLBAR 1043
#define IDC_ADVANCED_FORMAT_TOOLBAR 1044
#define IDC_SAVE_TOOLBAR 1045
#define IDC_HASH_TOOLBAR 1046
#define IDC_MULTI_TOOLBAR 1047
#define IDC_LANG 1051
#define IDC_ABOUT 1052
#define IDC_SETTINGS 1053
#define IDC_LOG 1054
#define IDC_LOG_EDIT 1055
#define IDC_LOG_SAVE 1056
#define IDC_LOG_CLEAR 1057
#define IDC_DONT_DISPLAY_AGAIN 1059
#define IDC_MORE_INFO 1060
#define IDC_POLICY 1061
#define IDC_UPDATE_FREQUENCY 1062
#define IDC_INCLUDE_BETAS 1063
#define IDC_RELEASE_NOTES 1064
#define IDC_DOWNLOAD 1065
#define IDC_CHECK_NOW 1066
#define IDC_WEBSITE 1067
#define IDC_YOUR_VERSION 1068
#define IDC_LATEST_VERSION 1069
#define IDC_DOWNLOAD_URL 1070
#define IDC_MD5 1071
#define IDC_SHA1 1072
#define IDC_SHA256 1073
#define IDC_SHA512 1074
#define IDC_SELECTION_ICON 1075
#define IDC_SELECTION_TEXT 1076
#define IDC_SELECTION_LINE 1077
#define IDC_SELECTION_CHOICE1 1078
#define IDC_SELECTION_CHOICE2 1079
#define IDC_SELECTION_CHOICE3 1080
#define IDC_SELECTION_CHOICE4 1081
#define IDC_SELECTION_CHOICE5 1082
#define IDC_SELECTION_CHOICE6 1083
#define IDC_SELECTION_CHOICE7 1084
#define IDC_SELECTION_CHOICE8 1085
#define IDC_SELECTION_CHOICE9 1086
#define IDC_SELECTION_CHOICE10 1087
#define IDC_SELECTION_CHOICE11 1088
#define IDC_SELECTION_CHOICE12 1089
#define IDC_SELECTION_CHOICE13 1090
#define IDC_SELECTION_CHOICE14 1091
#define IDC_SELECTION_CHOICE15 1092
#define IDC_SELECTION_CHOICEMAX 1093
#define IDC_SELECTION_USERNAME 1094
#define IDC_LIST_ICON 1095
#define IDC_LIST_TEXT 1096
#define IDC_LIST_LINE 1097
#define IDC_LIST_ITEM1 1098
#define IDC_LIST_ITEM2 1099
#define IDC_LIST_ITEM3 1100
#define IDC_LIST_ITEM4 1101
#define IDC_LIST_ITEM5 1102
#define IDC_LIST_ITEM6 1103
#define IDC_LIST_ITEM7 1104
#define IDC_LIST_ITEM8 1105
#define IDC_LIST_ITEM9 1106
#define IDC_LIST_ITEM10 1107
#define IDC_LIST_ITEM11 1108
#define IDC_LIST_ITEM12 1109
#define IDC_LIST_ITEM13 1110
#define IDC_LIST_ITEM14 1111
#define IDC_LIST_ITEM15 1112
#define IDC_LIST_ITEMMAX 1113
#define IDS_DEVICE_TXT 2000
#define IDS_PARTITION_TYPE_TXT 2001
#define IDS_FILE_SYSTEM_TXT 2002
#define IDS_CLUSTER_SIZE_TXT 2003
#define IDS_LABEL_TXT 2004
#define IDS_CSM_HELP_TXT 2005
#define IDS_UPDATE_SETTINGS_GRP 2006
#define IDS_UPDATE_FREQUENCY_TXT 2007
#define IDS_INCLUDE_BETAS_TXT 2008
#define IDS_NEW_VERSION_AVAIL_TXT 2009
#define IDS_NEW_VERSION_DOWNLOAD_GRP 2010
#define IDS_NEW_VERSION_NOTES_GRP 2011
#define IDS_CHECK_NOW_GRP 2012
#define IDS_TARGET_SYSTEM_TXT 2013
#define IDS_IMAGE_OPTION_TXT 2014
#define IDS_BOOT_SELECTION_TXT 2015
#define IDS_DRIVE_PROPERTIES_TXT 2016
#define IDS_FORMAT_OPTIONS_TXT 2017
#define IDS_STATUS_TXT 2018
#define MSG_000 3000
#define MSG_001 3001
#define MSG_002 3002
#define MSG_003 3003
#define MSG_004 3004
#define MSG_005 3005
#define MSG_006 3006
#define MSG_007 3007
#define MSG_008 3008
#define MSG_009 3009
#define MSG_010 3010
#define MSG_011 3011
#define MSG_012 3012
#define MSG_013 3013
#define MSG_014 3014
#define MSG_015 3015
#define MSG_016 3016
#define MSG_017 3017
#define MSG_018 3018
#define MSG_019 3019
#define MSG_020 3020
#define MSG_021 3021
#define MSG_022 3022
#define MSG_023 3023
#define MSG_024 3024
#define MSG_025 3025
#define MSG_026 3026
#define MSG_027 3027
#define MSG_028 3028
#define MSG_029 3029
#define MSG_030 3030
#define MSG_031 3031
#define MSG_032 3032
#define MSG_033 3033
#define MSG_034 3034
#define MSG_035 3035
#define MSG_036 3036
#define MSG_037 3037
#define MSG_038 3038
#define MSG_039 3039
#define MSG_040 3040
#define MSG_041 3041
#define MSG_042 3042
#define MSG_043 3043
#define MSG_044 3044
#define MSG_045 3045
#define MSG_046 3046
#define MSG_047 3047
#define MSG_048 3048
#define MSG_049 3049
#define MSG_050 3050
#define MSG_051 3051
#define MSG_052 3052
#define MSG_053 3053
#define MSG_054 3054
#define MSG_055 3055
#define MSG_056 3056
#define MSG_057 3057
#define MSG_058 3058
#define MSG_059 3059
#define MSG_060 3060
#define MSG_061 3061
#define MSG_062 3062
#define MSG_063 3063
#define MSG_064 3064
#define MSG_065 3065
#define MSG_066 3066
#define MSG_067 3067
#define MSG_068 3068
#define MSG_069 3069
#define MSG_070 3070
#define MSG_071 3071
#define MSG_072 3072
#define MSG_073 3073
#define MSG_074 3074
#define MSG_075 3075
#define MSG_076 3076
#define MSG_077 3077
#define MSG_078 3078
#define MSG_079 3079
#define MSG_080 3080
#define MSG_081 3081
#define MSG_082 3082
#define MSG_083 3083
#define MSG_084 3084
#define MSG_085 3085
#define MSG_086 3086
#define MSG_087 3087
#define MSG_088 3088
#define MSG_089 3089
#define MSG_090 3090
#define MSG_091 3091
#define MSG_092 3092
#define MSG_093 3093
#define MSG_094 3094
#define MSG_095 3095
#define MSG_096 3096
#define MSG_097 3097
#define MSG_098 3098
#define MSG_099 3099
#define MSG_100 3100
#define MSG_101 3101
#define MSG_102 3102
#define MSG_103 3103
#define MSG_104 3104
#define MSG_105 3105
#define MSG_106 3106
#define MSG_107 3107
#define MSG_108 3108
#define MSG_109 3109
#define MSG_110 3110
#define MSG_111 3111
#define MSG_112 3112
#define MSG_113 3113
#define MSG_114 3114
#define MSG_115 3115
#define MSG_116 3116
#define MSG_117 3117
#define MSG_118 3118
#define MSG_119 3119
#define MSG_120 3120
#define MSG_121 3121
#define MSG_122 3122
#define MSG_123 3123
#define MSG_124 3124
#define MSG_125 3125
#define MSG_126 3126
#define MSG_127 3127
#define MSG_128 3128
#define MSG_129 3129
#define MSG_130 3130
#define MSG_131 3131
#define MSG_132 3132
#define MSG_133 3133
#define MSG_134 3134
#define MSG_135 3135
#define MSG_136 3136
#define MSG_137 3137
#define MSG_138 3138
#define MSG_139 3139
#define MSG_140 3140
#define MSG_141 3141
#define MSG_142 3142
#define MSG_143 3143
#define MSG_144 3144
#define MSG_145 3145
#define MSG_146 3146
#define MSG_147 3147
#define MSG_148 3148
#define MSG_149 3149
#define MSG_150 3150
#define MSG_151 3151
#define MSG_152 3152
#define MSG_153 3153
#define MSG_154 3154
#define MSG_155 3155
#define MSG_156 3156
#define MSG_157 3157
#define MSG_158 3158
#define MSG_159 3159
#define MSG_160 3160
#define MSG_161 3161
#define MSG_162 3162
#define MSG_163 3163
#define MSG_164 3164
#define MSG_165 3165
#define MSG_166 3166
#define MSG_167 3167
#define MSG_168 3168
#define MSG_169 3169
#define MSG_170 3170
#define MSG_171 3171
#define MSG_172 3172
#define MSG_173 3173
#define MSG_174 3174
#define MSG_175 3175
#define MSG_176 3176
#define MSG_177 3177
#define MSG_178 3178
#define MSG_179 3179
#define MSG_180 3180
#define MSG_181 3181
#define MSG_182 3182
#define MSG_183 3183
#define MSG_184 3184
#define MSG_185 3185
#define MSG_186 3186
#define MSG_187 3187
#define MSG_188 3188
#define MSG_189 3189
#define MSG_190 3190
#define MSG_191 3191
#define MSG_192 3192
#define MSG_193 3193
#define MSG_194 3194
#define MSG_195 3195
#define MSG_196 3196
#define MSG_197 3197
#define MSG_198 3198
#define MSG_199 3199
#define MSG_200 3200
#define MSG_201 3201
#define MSG_202 3202
#define MSG_203 3203
#define MSG_204 3204
#define MSG_205 3205
#define MSG_206 3206
#define MSG_207 3207
#define MSG_208 3208
#define MSG_209 3209
#define MSG_210 3210
#define MSG_211 3211
#define MSG_212 3212
#define MSG_213 3213
#define MSG_214 3214
#define MSG_215 3215
#define MSG_216 3216
#define MSG_217 3217
#define MSG_218 3218
#define MSG_219 3219
#define MSG_220 3220
#define MSG_221 3221
#define MSG_222 3222
#define MSG_223 3223
#define MSG_224 3224
#define MSG_225 3225
#define MSG_226 3226
#define MSG_227 3227
#define MSG_228 3228
#define MSG_229 3229
#define MSG_230 3230
#define MSG_231 3231
#define MSG_232 3232
#define MSG_233 3233
#define MSG_234 3234
#define MSG_235 3235
#define MSG_236 3236
#define MSG_237 3237
#define MSG_238 3238
#define MSG_239 3239
#define MSG_240 3240
#define MSG_241 3241
#define MSG_242 3242
#define MSG_243 3243
#define MSG_244 3244
#define MSG_245 3245
#define MSG_246 3246
#define MSG_247 3247
#define MSG_248 3248
#define MSG_249 3249
#define MSG_250 3250
#define MSG_251 3251
#define MSG_252 3252
#define MSG_253 3253
#define MSG_254 3254
#define MSG_255 3255
#define MSG_256 3256
#define MSG_257 3257
#define MSG_258 3258
#define MSG_259 3259
#define MSG_260 3260
#define MSG_261 3261
#define MSG_262 3262
#define MSG_263 3263
#define MSG_264 3264
#define MSG_265 3265
#define MSG_266 3266
#define MSG_267 3267
#define MSG_268 3268
#define MSG_269 3269
#define MSG_270 3270
#define MSG_271 3271
#define MSG_272 3272
#define MSG_273 3273
#define MSG_274 3274
#define MSG_275 3275
#define MSG_276 3276
#define MSG_277 3277
#define MSG_278 3278
#define MSG_279 3279
#define MSG_280 3280
#define MSG_281 3281
#define MSG_282 3282
#define MSG_283 3283
#define MSG_284 3284
#define MSG_285 3285
#define MSG_286 3286
#define MSG_287 3287
#define MSG_288 3288
#define MSG_289 3289
#define MSG_290 3290
#define MSG_291 3291
#define MSG_292 3292
#define MSG_293 3293
#define MSG_294 3294
#define MSG_295 3295
#define MSG_296 3296
#define MSG_297 3297
#define MSG_298 3298
#define MSG_299 3299
#define MSG_300 3300
#define MSG_301 3301
#define MSG_302 3302
#define MSG_303 3303
#define MSG_304 3304
#define MSG_305 3305
#define MSG_306 3306
#define MSG_307 3307
#define MSG_308 3308
#define MSG_309 3309
#define MSG_310 3310
#define MSG_311 3311
#define MSG_312 3312
#define MSG_313 3313
#define MSG_314 3314
#define MSG_315 3315
#define MSG_316 3316
#define MSG_317 3317
#define MSG_318 3318
#define MSG_319 3319
#define MSG_320 3320
#define MSG_321 3321
#define MSG_322 3322
#define MSG_323 3323
#define MSG_324 3324
#define MSG_325 3325
#define MSG_326 3326
#define MSG_327 3327
#define MSG_328 3328
#define MSG_329 3329
#define MSG_330 3330
#define MSG_331 3331
#define MSG_332 3332
#define MSG_333 3333
#define MSG_334 3334
#define MSG_335 3335
#define MSG_336 3336
#define MSG_337 3337
#define MSG_338 3338
#define MSG_339 3339
#define MSG_340 3340
#define MSG_341 3341
#define MSG_342 3342
#define MSG_343 3343
#define MSG_344 3344
#define MSG_345 3345
#define MSG_346 3346
#define MSG_347 3347
#define MSG_348 3348
#define MSG_349 3349
#define MSG_350 3350
#define MSG_351 3351
#define MSG_352 3352
#define MSG_353 3353
#define MSG_354 3354
#define MSG_355 3355
#define MSG_356 3356
#define MSG_357 3357
#define MSG_358 3358
#define MSG_359 3359
#define MSG_360 3360
#define MSG_361 3361
#define MSG_362 3362
#define MSG_363 3363
#define MSG_364 3364
#define MSG_365 3365
#define MSG_366 3366
#define MSG_367 3367
#define MSG_368 3368
#define MSG_369 3369
#define MSG_370 3370
#define MSG_371 3371
#define MSG_372 3372
#define MSG_373 3373
#define MSG_374 3374
#define MSG_375 3375
#define MSG_376 3376
#define MSG_377 3377
#define MSG_378 3378
#define MSG_379 3379
#define MSG_380 3380
#define MSG_381 3381
#define MSG_382 3382
#define MSG_383 3383
#define MSG_384 3384
#define MSG_385 3385
#define MSG_386 3386
#define MSG_387 3387
#define MSG_388 3388
#define MSG_389 3389
#define MSG_390 3390
#define MSG_391 3391
#define MSG_392 3392
#define MSG_393 3393
#define MSG_394 3394
#define MSG_395 3395
#define MSG_396 3396
#define MSG_397 3397
#define MSG_398 3398
#define MSG_399 3399
#define MSG_MAX 3400
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NO_MFC 1
#define _APS_NEXT_RESOURCE_VALUE 505
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1114
#define _APS_NEXT_SYMED_VALUE 4000
#endif
#endif
| 28,033 |
C
|
.c
| 616 | 43.503247 | 62 | 0.414919 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
4,689 |
rock.c
|
pbatard_rufus/src/libcdio/iso9660/rock.c
|
/*
Copyright (C) 2020, 2023 Pete Batard <[email protected]>
Copyright (C) 2005, 2008, 2010-2011, 2014, 2017, 2022 Rocky Bernstein
<[email protected]>
Adapted from GNU/Linux fs/isofs/rock.c (C) 1992, 1993 Eric Youngdale
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/>.
*/
/* Rock Ridge Extensions to iso9660 */
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#ifdef HAVE_STRING_H
# include <string.h>
#endif
#ifdef HAVE_STDLIB_H
# include <stdlib.h>
#endif
#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif
#include <cdio/iso9660.h>
#include <cdio/logging.h>
#include <cdio/bytesex.h>
#include "filemode.h"
#include "cdio_private.h"
#define CDIO_MKDEV(ma,mi) ((ma)<<16 | (mi))
enum iso_rock_enums iso_rock_enums;
iso_rock_nm_flag_t iso_rock_nm_flag;
iso_rock_sl_flag_t iso_rock_sl_flag;
iso_rock_tf_flag_t iso_rock_tf_flag;
/* Used by get_rock_ridge_filename() */
extern iso9660_stat_t*
_iso9660_dd_find_lsn(void* p_image, lsn_t i_lsn);
/* Our own realloc routine tailored for the iso9660_stat_t symlink
field. I can't figure out how to make realloc() work without
valgrind complaint.
*/
static bool
realloc_symlink(/*in/out*/ iso9660_stat_t *p_stat, uint8_t i_grow)
{
if (!p_stat->rr.i_symlink) {
const uint16_t i_max = 2*i_grow+1;
p_stat->rr.psz_symlink = (char *) calloc(1, i_max);
p_stat->rr.i_symlink_max = i_max;
return (NULL != p_stat->rr.psz_symlink);
} else {
unsigned int i_needed = p_stat->rr.i_symlink + i_grow ;
if ( i_needed <= p_stat->rr.i_symlink_max)
return true;
else {
char * psz_newsymlink = (char *) calloc(1, 2*i_needed);
if (!psz_newsymlink) return false;
p_stat->rr.i_symlink_max = 2*i_needed;
memcpy(psz_newsymlink, p_stat->rr.psz_symlink, p_stat->rr.i_symlink);
free(p_stat->rr.psz_symlink);
p_stat->rr.psz_symlink = psz_newsymlink;
return true;
}
}
}
/* These functions are designed to read the system areas of a directory record
* and extract relevant information. There are different functions provided
* depending upon what information we need at the time. One function fills
* out an inode structure, a second one extracts a filename, a third one
* returns a symbolic link name, and a fourth one returns the extent number
* for the file. */
#define SIG(A,B) ((A) | ((B) << 8)) /* isonum_721() */
/* This is a way of ensuring that we have something in the system
use fields that is compatible with Rock Ridge */
#define CHECK_SP(FAIL) \
if (rr->u.SP.magic[0] != 0xbe) FAIL; \
if (rr->u.SP.magic[1] != 0xef) FAIL; \
p_stat->rr.s_rock_offset = rr->u.SP.skip;
/* We define a series of macros because each function must do exactly the
same thing in certain places. We use the macros to ensure that everything
is done correctly */
#define CONTINUE_DECLS \
uint32_t cont_extent = 0, cont_offset = 0, cont_size = 0; \
uint8_t *buffer = NULL, ce_count = 0
#define CHECK_CE(FAIL) \
{ cont_extent = from_733(rr->u.CE.extent); \
cont_offset = from_733(rr->u.CE.offset); \
if (cont_offset >= ISO_BLOCKSIZE) FAIL; \
cont_size = from_733(rr->u.CE.size); \
if (cont_size >= ISO_BLOCKSIZE) FAIL; \
}
#define SETUP_ROCK_RIDGE(DE, CHR, LEN) \
{ \
LEN= sizeof(iso9660_dir_t) + DE->filename.len; \
if (LEN & 1) LEN++; \
CHR = ((unsigned char *) DE) + LEN; \
LEN = *((unsigned char *) DE) - LEN; \
if (0xff != p_stat->rr.s_rock_offset) \
{ \
LEN -= p_stat->rr.s_rock_offset; \
CHR += p_stat->rr.s_rock_offset; \
if (LEN<0) LEN=0; \
} \
}
/* Copy a long or short time from the iso_rock_tf_t into
the specified field of a iso_rock_statbuf_t.
non-paramater variables are p_stat, rr, and cnt.
*/
#define add_time(FLAG, TIME_FIELD) \
if (rr->u.TF.flags & FLAG) { \
p_stat->rr.TIME_FIELD.b_used = true; \
p_stat->rr.TIME_FIELD.b_longdate = \
(0 != (rr->u.TF.flags & ISO_ROCK_TF_LONG_FORM)); \
if (p_stat->rr.TIME_FIELD.b_longdate) { \
memcpy(&(p_stat->rr.TIME_FIELD.t.ltime), \
&(rr->u.TF.time_bytes[cnt]), \
sizeof(iso9660_ltime_t)); \
cnt += sizeof(iso9660_ltime_t); \
} else { \
memcpy(&(p_stat->rr.TIME_FIELD.t.dtime), \
&(rr->u.TF.time_bytes[cnt]), \
sizeof(iso9660_dtime_t)); \
cnt += sizeof(iso9660_dtime_t); \
} \
}
/* Indicates if we should process deep directory entries */
static inline bool
is_rr_dd_enabled(void * p_image) {
cdio_header_t* p_header = (cdio_header_t*)p_image;
if (!p_header)
return false;
return !(p_header->u_flags & CDIO_HEADER_FLAGS_DISABLE_RR_DD);
}
/*!
Get
@return length of name field; 0: not found, -1: to be ignored
*/
int
get_rock_ridge_filename(iso9660_dir_t * p_iso9660_dir,
/*in*/ void * p_image,
/*out*/ char * psz_name,
/*in/out*/ iso9660_stat_t *p_stat)
{
int len;
unsigned char *chr;
int symlink_len = 0;
CONTINUE_DECLS;
int i_namelen = 0;
int truncate=0;
if (!p_stat || nope == p_stat->rr.b3_rock)
return 0;
*psz_name = 0;
SETUP_ROCK_RIDGE(p_iso9660_dir, chr, len);
repeat:
{
iso_extension_record_t * rr;
int sig;
int rootflag;
while (len > 1){ /* There may be one byte for padding somewhere */
rr = (iso_extension_record_t *) chr;
sig = *chr+(*(chr+1) << 8);
/* We used to check for some valid values of SIG, specifically
SP, CE, ER, RR, PX, PN, SL, NM, CL, PL, TF, and ZF.
However there are various extensions to this set. So we
skip checking now.
*/
if (rr->len == 0)
goto out; /* Something got screwed up here */
chr += rr->len;
len -= rr->len;
switch(sig) {
case SIG('S','P'):
CHECK_SP({cdio_warn("Invalid Rock Ridge SP field"); goto out;});
p_stat->rr.u_su_fields |= ISO_ROCK_SUF_SP;
break;
case SIG('C','E'):
{
iso711_t i_fname = from_711(p_iso9660_dir->filename.len);
if ('\0' == p_iso9660_dir->filename.str[1] && 1 == i_fname)
break;
if ('\1' == p_iso9660_dir->filename.str[1] && 1 == i_fname)
break;
}
CHECK_CE({cdio_warn("Invalid Rock Ridge CE field"); goto out;});
p_stat->rr.u_su_fields |= ISO_ROCK_SUF_CE;
/* Though no mastering utility in its right mind would produce anything
like this, the specs make it theoretically possible to have more RR
extensions after a CE, so we delay the CE block processing for later.
*/
break;
case SIG('E','R'):
cdio_debug("ISO 9660 Extensions: ");
{
int p;
for (p=0; p < rr->u.ER.len_id; p++)
cdio_debug("%c", rr->u.ER.data[p]);
}
break;
case SIG('N','M'):
/* Alternate name */
p_stat->rr.u_su_fields |= ISO_ROCK_SUF_NM;
if (truncate)
break;
if (rr->u.NM.flags & ISO_ROCK_NM_PARENT) {
i_namelen = sizeof("..");
strncat(psz_name, "..", i_namelen);
break;
} else if (rr->u.NM.flags & ISO_ROCK_NM_CURRENT) {
i_namelen = sizeof(".");
strncat(psz_name, ".", i_namelen);
break;
}
if (rr->u.NM.flags & ~1) {
cdio_info("Unsupported NM flag settings (%d)",rr->u.NM.flags);
break;
}
if((strlen(psz_name) + rr->len - 5) >= 254) {
truncate = 1;
break;
}
strncat(psz_name, rr->u.NM.name, rr->len - 5);
i_namelen += rr->len - 5;
break;
case SIG('P','X'):
/* POSIX file attributes */
p_stat->rr.st_mode = from_733(rr->u.PX.st_mode);
p_stat->rr.st_nlinks = from_733(rr->u.PX.st_nlinks);
p_stat->rr.st_uid = from_733(rr->u.PX.st_uid);
p_stat->rr.st_gid = from_733(rr->u.PX.st_gid);
p_stat->rr.u_su_fields |= ISO_ROCK_SUF_PX;
break;
case SIG('S','L'):
{
/* Symbolic link */
uint8_t slen;
iso_rock_sl_part_t * p_sl;
iso_rock_sl_part_t * p_oldsl;
slen = rr->len - 5;
p_sl = &rr->u.SL.link;
p_stat->rr.i_symlink = symlink_len;
p_stat->rr.u_su_fields |= ISO_ROCK_SUF_SL;
while (slen > 1){
rootflag = 0;
switch(p_sl->flags &~1){
case 0:
realloc_symlink(p_stat, p_sl->len);
memcpy(&(p_stat->rr.psz_symlink[p_stat->rr.i_symlink]),
p_sl->text, p_sl->len);
p_stat->rr.i_symlink += p_sl->len;
break;
case 4:
realloc_symlink(p_stat, 1);
p_stat->rr.psz_symlink[p_stat->rr.i_symlink++] = '.';
/* continue into next case. */
case 2:
realloc_symlink(p_stat, 1);
p_stat->rr.psz_symlink[p_stat->rr.i_symlink++] = '.';
break;
case 8:
rootflag = 1;
realloc_symlink(p_stat, 1);
p_stat->rr.psz_symlink[p_stat->rr.i_symlink++] = '/';
break;
default:
cdio_warn("Symlink component flag not implemented");
}
slen -= p_sl->len + 2;
p_oldsl = p_sl;
p_sl = (iso_rock_sl_part_t *) (((char *) p_sl) + p_sl->len + 2);
if (slen < 2) {
if (((rr->u.SL.flags & 1) != 0) && ((p_oldsl->flags & 1) == 0))
p_stat->rr.i_symlink += 1;
break;
}
/*
* If this component record isn't continued, then append a '/'.
*/
if (!rootflag && (p_oldsl->flags & 1) == 0) {
realloc_symlink(p_stat, 1);
p_stat->rr.psz_symlink[p_stat->rr.i_symlink++] = '/';
}
}
}
symlink_len = p_stat->rr.i_symlink;
realloc_symlink(p_stat, 1);
p_stat->rr.psz_symlink[symlink_len]='\0';
break;
case SIG('T','F'):
/* Time stamp(s) for a file */
{
int cnt = 0;
add_time(ISO_ROCK_TF_CREATE, create);
add_time(ISO_ROCK_TF_MODIFY, modify);
add_time(ISO_ROCK_TF_ACCESS, access);
add_time(ISO_ROCK_TF_ATTRIBUTES, attributes);
add_time(ISO_ROCK_TF_BACKUP, backup);
add_time(ISO_ROCK_TF_EXPIRATION, expiration);
add_time(ISO_ROCK_TF_EFFECTIVE, effective);
p_stat->rr.u_su_fields |= ISO_ROCK_SUF_TF;
break;
}
case SIG('C','L'):
/* Child Link for a deep directory */
if (!is_rr_dd_enabled(p_image))
break;
{
iso9660_stat_t* target = NULL;
p_stat->rr.u_su_fields |= ISO_ROCK_SUF_CL;
target = _iso9660_dd_find_lsn(p_image, from_733(rr->u.PL.location));
if (!target) {
cdio_warn("Could not get Rock Ridge deep directory child");
break;
}
memcpy(p_stat, target, sizeof(iso9660_stat_t));
/* Prevent the symlink from being freed on the duplicated struct */
target->rr.psz_symlink = NULL;
iso9660_stat_free(target);
}
break;
case SIG('P','L'):
/* Parent link of a deep directory */
if (is_rr_dd_enabled(p_image))
p_stat->rr.u_su_fields |= ISO_ROCK_SUF_PL;
break;
case SIG('R','E'):
/* Relocated entry for a deep directory */
if (is_rr_dd_enabled(p_image))
p_stat->rr.u_su_fields |= ISO_ROCK_SUF_RE;
break;
case SIG('S','F'):
/* Sparse File */
p_stat->rr.u_su_fields |= ISO_ROCK_SUF_SF;
cdio_warn("Rock Ridge Sparse File detected");
break;
default:
break;
}
}
}
/* Process delayed CE blocks */
if (cont_size != 0) {
free(buffer);
buffer = calloc(1, ISO_BLOCKSIZE);
if (!buffer)
goto out;
if (iso9660_iso_seek_read(p_image, buffer, cont_extent, 1) != ISO_BLOCKSIZE)
goto out;
chr = &buffer[cont_offset];
len = cont_size;
cont_size = 0;
/* Someone abusing the specs may also be creating looping CEs */
if (ce_count++ < 64)
goto repeat;
else
cdio_warn("More than 64 consecutive Rock Ridge CEs detected");
}
if (p_stat->rr.u_su_fields & ISO_ROCK_SUF_FORMAL)
p_stat->rr.b3_rock = yep;
free(buffer);
return i_namelen; /* If 0, this file did not have a NM field */
out:
free(buffer);
return 0;
}
#define BUF_COUNT 16
#define BUF_SIZE sizeof("drwxrwxrwx")
/* Return a pointer to a internal free buffer */
static char *
_getbuf (void)
{
static char _buf[BUF_COUNT][BUF_SIZE];
static int _i = -1;
_i++;
_i %= BUF_COUNT;
memset (_buf[_i], 0, BUF_SIZE);
return _buf[_i];
}
/*!
Returns a string which interpreting the POSIX mode st_mode.
For example:
\verbatim
drwxrws---
-rw-rw-r--
lrwxrwxrwx
\endverbatim
A description of the characters in the string follows
The 1st character is either "b" for a block device,
"c" for a character device, "d" if the entry is a directory, "l" for
a symbolic link, "p" for a pipe or FIFO, "s" for a "socket",
or "-" if none of the these.
The 2nd to 4th characters refer to permissions for a user while the
the 5th to 7th characters refer to permissions for a group while, and
the 8th to 10h characters refer to permissions for everyone.
In each of these triplets the first character (2, 5, 8) is "r" if
the entry is allowed to be read.
The second character of a triplet (3, 6, 9) is "w" if the entry is
allowed to be written.
The third character of a triplet (4, 7, 10) is "x" if the entry is
executable but not user (for character 4) or group (for characters
6) settable and "s" if the item has the corresponding user/group set.
For a directory having an executable property on ("x" or "s") means
the directory is allowed to be listed or "searched". If the execute
property is not allowed for a group or user but the corresponding
group/user is set "S" indicates this. If none of these properties
holds the "-" indicates this.
*/
const char *
iso9660_get_rock_attr_str(posix_mode_t st_mode)
{
char *result = _getbuf();
if (S_ISBLK(st_mode))
result[ 0] = 'b';
else if (S_ISDIR(st_mode))
result[ 0] = 'd';
else if (S_ISCHR(st_mode))
result[ 0] = 'c';
else if (S_ISLNK(st_mode))
result[ 0] = 'l';
else if (S_ISFIFO(st_mode))
result[ 0] = 'p';
else if (S_ISSOCK(st_mode))
result[ 0] = 's';
/* May eventually fill in others.. */
else
result[ 0] = '-';
result[ 1] = (st_mode & ISO_ROCK_IRUSR) ? 'r' : '-';
result[ 2] = (st_mode & ISO_ROCK_IWUSR) ? 'w' : '-';
if (st_mode & ISO_ROCK_ISUID)
result[ 3] = (st_mode & ISO_ROCK_IXUSR) ? 's' : 'S';
else
result[ 3] = (st_mode & ISO_ROCK_IXUSR) ? 'x' : '-';
result[ 4] = (st_mode & ISO_ROCK_IRGRP) ? 'r' : '-';
result[ 5] = (st_mode & ISO_ROCK_IWGRP) ? 'w' : '-';
if (st_mode & ISO_ROCK_ISGID)
result[ 6] = (st_mode & ISO_ROCK_IXGRP) ? 's' : 'S';
else
result[ 6] = (st_mode & ISO_ROCK_IXGRP) ? 'x' : '-';
result[ 7] = (st_mode & ISO_ROCK_IROTH) ? 'r' : '-';
result[ 8] = (st_mode & ISO_ROCK_IWOTH) ? 'w' : '-';
result[ 9] = (st_mode & ISO_ROCK_IXOTH) ? 'x' : '-';
result[10] = '\0';
return result;
}
/*!
Returns POSIX mode bitstring for a given file.
*/
mode_t
iso9660_get_posix_filemode_from_rock(const iso_rock_statbuf_t *rr)
{
return (mode_t) rr->st_mode;
}
| 15,063 |
C
|
.c
| 455 | 29.301099 | 82 | 0.626537 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
4,696 |
mmc_private.h
|
pbatard_rufus/src/libcdio/mmc/mmc_private.h
|
/* placeholder for unused MMC helper routines. */
typedef driver_return_code_t (*mmc_run_cmd_fn_t) ( void );
| 110 |
C
|
.c
| 2 | 53.5 | 58 | 0.719626 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,704 |
util.c
|
pbatard_rufus/src/libcdio/driver/util.c
|
/*
Copyright (C) 2003, 2004, 2005, 2008, 2009, 2010, 2011
Rocky Bernstein <[email protected]>
Copyright (C) 2000 Herbert Valerio Riedel <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
# define __CDIO_CONFIG_H__ 1
#endif
#include <ctype.h>
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STDIO_H
#include <stdio.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_INTTYPES_H
#include "inttypes.h"
#endif
#include <ctype.h>
#include "cdio_assert.h"
#include <cdio/types.h>
#include <cdio/util.h>
#include <cdio/version.h>
size_t
_cdio_strlenv(char **str_array)
{
size_t n = 0;
cdio_assert (str_array != NULL);
while(str_array[n])
n++;
return n;
}
void
_cdio_strfreev(char **strv)
{
int n;
cdio_assert (strv != NULL);
if (strv == NULL)
return;
for(n = 0; strv[n]; n++)
free(strv[n]);
free(strv);
}
char **
_cdio_strsplit(const char str[], char delim) /* fixme -- non-reentrant */
{
int n;
char **strv = NULL;
char *_str, *p;
char _delim[2] = { 0, 0 };
cdio_assert (str != NULL);
_str = strdup(str);
_delim[0] = delim;
cdio_assert (_str != NULL);
n = 1;
p = _str;
while(*p)
if (*(p++) == delim)
n++;
strv = calloc (n+1, sizeof (char *));
cdio_assert (strv != NULL);
n = 0;
while((p = strtok(n ? NULL : _str, _delim)) != NULL)
strv[n++] = strdup(p);
free(_str);
return strv;
}
void *
_cdio_memdup (const void *mem, size_t count)
{
void *new_mem = NULL;
if (mem)
{
new_mem = calloc (1, count);
cdio_assert (new_mem != NULL);
memcpy (new_mem, mem, count);
}
return new_mem;
}
char *
_cdio_strdup_upper (const char str[])
{
char *new_str = NULL;
if (str)
{
char *p;
p = new_str = strdup (str);
while (*p)
{
*p = toupper ((unsigned char) *p);
p++;
}
}
return new_str;
}
int
_cdio_stricmp (const char str1[], const char str2[])
{
if (str1 && str2) {
int c1, c2;
do {
c1 = tolower((unsigned char)*str1++);
c2 = tolower((unsigned char)*str2++);
} while (c1 == c2 && c1 != '\0');
return c1 - c2;
} else return (str1 != str2);
}
int
_cdio_strnicmp(const char str1[], const char str2[], size_t count)
{
if (str1 && str2) {
int c1 = 0, c2 = 0;
size_t i;
for (i = 0; i < count; i++) {
c1 = tolower((unsigned char)*str1++);
c2 = tolower((unsigned char)*str2++);
if (c1 != c2 || c1 == '\0')
break;
}
return c1 - c2;
} else return (str1 != str2);
}
/* Convert MinGW/MSYS paths that start in "/c/..." to "c:/..."
so that they can be used with fopen(), stat(), etc.
Returned string must be freed by the caller using cdio_free().*/
char *
_cdio_strdup_fixpath (const char path[])
{
char *new_path = NULL;
if (path)
{
new_path = strdup (path);
#if defined(_WIN32)
if (new_path && (strlen (new_path) >= 3) && (new_path[0] == '/') &&
(new_path[2] == '/') && (isalpha (new_path[1])))
{
new_path[0] = new_path[1];
new_path[1] = ':';
}
#endif
}
return new_path;
}
uint8_t
cdio_to_bcd8 (uint8_t n)
{
/*cdio_assert (n < 100);*/
return ((n/10)<<4) | (n%10);
}
uint8_t
cdio_from_bcd8(uint8_t p)
{
return (0xf & p)+(10*(p >> 4));
}
const char *cdio_version_string = CDIO_VERSION;
const unsigned int libcdio_version_num = LIBCDIO_VERSION_NUM;
/*
* Local variables:
* c-file-style: "gnu"
* tab-width: 8
* indent-tabs-mode: nil
* End:
*/
| 4,204 |
C
|
.c
| 177 | 20.19209 | 74 | 0.607789 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
4,718 |
dumpdir.c
|
pbatard_rufus/src/syslinux/libfat/dumpdir.c
|
/* ----------------------------------------------------------------------- *
*
* Copyright 2019 Pete Batard <[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, Inc., 53 Temple Place Ste 330,
* Boston MA 02111-1307, USA; either version 2 of the License, or
* (at your option) any later version; incorporated herein by reference.
*
* ----------------------------------------------------------------------- */
/*
* dumpdir.c
*
* Returns all files and directory items from a FAT directory.
*/
#include <string.h>
#include "libfatint.h"
static struct fat_dirent* get_next_dirent(struct libfat_filesystem *fs,
libfat_sector_t *sector, int *offset)
{
struct fat_dirent *dep;
*offset += sizeof(struct fat_dirent);
if (*offset >= LIBFAT_SECTOR_SIZE) {
*offset = 0;
*sector = libfat_nextsector(fs, *sector);
if ((*sector == 0) || (*sector == (libfat_sector_t)-1))
return NULL;
}
dep = libfat_get_sector(fs, *sector);
if (!dep)
return NULL;
dep = (struct fat_dirent*) &((char*)dep)[*offset];
return dep;
}
static void fill_utf16(wchar_t *name, unsigned char *entry)
{
int i;
for (i=0; i<5; i++)
name[i] = read16((le16_t*)&entry[1 + 2*i]);
for (i=5; i<11; i++)
name[i] = read16((le16_t*)&entry[4 + 2*i]);
for (i=11; i<12; i++)
name[i] = read16((le16_t*)&entry[6 + 2*i]);
}
int libfat_dumpdir(struct libfat_filesystem *fs, libfat_dirpos_t *dp,
libfat_diritem_t *di)
{
int i, j;
struct fat_dirent *dep;
memset(di->name, 0, sizeof(di->name));
di->size = 0;
di->attributes = 0;
if (dp->offset < 0) {
/* First entry */
dp->offset = 0;
dp->sector = libfat_clustertosector(fs, dp->cluster);
if ((dp->sector == 0) || (dp->sector == (libfat_sector_t)-1))
return -1;
dep = libfat_get_sector(fs, dp->sector);
} else {
dep = get_next_dirent(fs, &dp->sector, &dp->offset);
}
if (!dep)
return -1; /* Read error */
/* Ignore volume labels, deleted entries as well as '.' and '..' entries */
while ((dep->attribute == 0x08) || (dep->name[0] == 0xe5) ||
((dep->name[0] == '.') && (dep->name[2] == ' ') &&
((dep->name[1] == ' ') || (dep->name[1] == '.')))) {
dep = get_next_dirent(fs, &dp->sector, &dp->offset);
if (!dep)
return -1;
}
if (dep->name[0] == 0)
return -2; /* Last entry */
/* Build UCS-2 name */
j = -1;
while (dep->attribute == 0x0F) { /* LNF (Long File Name) entry */
i = dep->name[0];
if ((j < 0) && ((i & 0xF0) != 0x40)) /* End of LFN marker was not found */
break;
/* Isolate and check the sequence number, which should be decrementing */
i = (i & 0x0F) - 1;
if ((j >= 0) && (i != j - 1))
return -3;
j = i;
fill_utf16(&di->name[13 * i], dep->name);
dep = get_next_dirent(fs, &dp->sector, &dp->offset);
if (!dep)
return -1;
}
if (di->name[0] == 0) {
for (i = 0, j = 0; i < 12; i++) {
if ((i >= 8) && (dep->name[i] == ' '))
break;
if (i == 8)
di->name[j++] = '.';
if (dep->name[i] == ' ')
continue;
di->name[j] = dep->name[i];
/* Caseflags: bit 3 = lowercase basename, bit 4 = lowercase extension */
if ((di->name[j] >= 'A') && (di->name[j] <= 'Z')) {
if ((dep->caseflags & 0x02) && (i < 8))
di->name[j] += 0x20;
if ((dep->caseflags & 0x04) && (i >= 8))
di->name[j] += 0x20;
}
j++;
}
}
di->attributes = dep->attribute & 0x37;
di->size = read32(&dep->size);
return read16(&dep->clustlo) + (read16(&dep->clusthi) << 16);
}
| 3,662 |
C
|
.c
| 114 | 28.464912 | 79 | 0.545814 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,787 |
fat12.c
|
pbatard_rufus/src/ms-sys/fat12.c
|
/******************************************************************
Copyright (C) 2009 Henrik Carlqvist
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., 675 Mass Ave, Cambridge, MA 02139, USA.
******************************************************************/
#include <stdio.h>
#include <string.h>
#include "file.h"
#include "fat12.h"
int is_fat_12_fs(FILE *fp)
{
char *szMagic = "FAT12 ";
return contains_data(fp, 0x36, szMagic, strlen(szMagic));
} /* is_fat_12_fs */
int entire_fat_12_br_matches(FILE *fp)
{
#include "br_fat12_0x0.h"
#include "br_fat12_0x3e.h"
return
( contains_data(fp, 0x0, br_fat12_0x0, sizeof(br_fat12_0x0)) &&
/* BIOS Parameter Block might differ between systems */
contains_data(fp, 0x3e, br_fat12_0x3e, sizeof(br_fat12_0x3e)) );
} /* entire_fat_12_br_matches */
int write_fat_12_br(FILE *fp, int bKeepLabel)
{
#include "label_11_char.h"
#include "br_fat12_0x0.h"
#include "br_fat12_0x3e.h"
if(bKeepLabel)
return
( write_data(fp, 0x0, br_fat12_0x0, sizeof(br_fat12_0x0)) &&
/* BIOS Parameter Block might differ between systems */
write_data(fp, 0x3e, br_fat12_0x3e, sizeof(br_fat12_0x3e)) );
else
return
( write_data(fp, 0x0, br_fat12_0x0, sizeof(br_fat12_0x0)) &&
/* BIOS Parameter Block might differ between systems */
write_data(fp, 0x2b, label_11_char, sizeof(label_11_char)) &&
write_data(fp, 0x3e, br_fat12_0x3e, sizeof(br_fat12_0x3e)) );
} /* write_fat_12_br */
| 2,100 |
C
|
.c
| 49 | 39.163265 | 72 | 0.658011 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,788 |
ntfs.c
|
pbatard_rufus/src/ms-sys/ntfs.c
|
/******************************************************************
Copyright (C) 2012 Pete Batard <[email protected]>
Based on fat16.c Copyright (C) 2009 Henrik Carlqvist
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., 675 Mass Ave, Cambridge, MA 02139, USA.
******************************************************************/
#include <stdio.h>
#include <string.h>
#include "file.h"
#include "ntfs.h"
int is_ntfs_fs(FILE *fp)
{
unsigned char aucMagic[] = {'N','T','F','S',' ',' ',' ',' '};
return contains_data(fp, 0x03, aucMagic, sizeof(aucMagic));
} /* is_ntfs_fs */
int is_ntfs_br(FILE *fp)
{
/* A "file" is probably some kind of NTFS boot record if it contains the
magic chars 0x55, 0xAA at positions 0x1FE */
unsigned char aucRef[] = {0x55, 0xAA};
unsigned char aucMagic[] = {'N','T','F','S',' ',' ',' ',' '};
if( ! contains_data(fp, 0x1FE, aucRef, sizeof(aucRef)))
return 0;
if( ! contains_data(fp, 0x03, aucMagic, sizeof(aucMagic)))
return 0;
return 1;
} /* is_ntfs_br */
int entire_ntfs_br_matches(FILE *fp)
{
#include "br_ntfs_0x0.h"
#include "br_ntfs_0x54.h"
return
( contains_data(fp, 0x0, br_ntfs_0x0, sizeof(br_ntfs_0x0)) &&
/* BIOS Parameter Block might differ between systems */
contains_data(fp, 0x54, br_ntfs_0x54, sizeof(br_ntfs_0x54)) );
} /* entire_ntfs_br_matches */
int write_ntfs_br(FILE *fp)
{
#include "br_ntfs_0x0.h"
#include "br_ntfs_0x54.h"
return
( write_data(fp, 0x0, br_ntfs_0x0, sizeof(br_ntfs_0x0)) &&
/* BIOS Parameter Block should not be overwritten */
write_data(fp, 0x54, br_ntfs_0x54, sizeof(br_ntfs_0x54)) );
} /* write_ntsf_br */
| 2,282 |
C
|
.c
| 54 | 38.611111 | 75 | 0.641084 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,789 |
br.c
|
pbatard_rufus/src/ms-sys/br.c
|
/******************************************************************
Copyright (C) 2009-2015 Henrik Carlqvist
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., 675 Mass Ave, Cambridge, MA 02139, USA.
******************************************************************/
#include <stdio.h>
#include "file.h"
#include "nls.h"
#include "br.h"
unsigned long ulBytesPerSector = 512;
void set_bytes_per_sector(unsigned long ulValue)
{
ulBytesPerSector = ulValue;
if ((ulBytesPerSector < 512) || (ulBytesPerSector > 65536))
ulBytesPerSector = 512;
} /* set_bytes_per_sector */
uint32_t read_windows_disk_signature(FILE *fp)
{
uint32_t tWDS;
if(!read_data(fp, 0x1b8, &tWDS, 4))
return 0;
return tWDS;
} /* read_windows_disk_signature */
int write_windows_disk_signature(FILE *fp, uint32_t tWDS)
{
return write_data(fp, 0x1b8, &tWDS, 4);
} /* write_windows_disk_signature */
uint16_t read_mbr_copy_protect_bytes(FILE *fp)
{
uint16_t tOut;
if(!read_data(fp, 0x1bc, &tOut, 2))
return 0xffff;
return tOut;
} /* read_mbr_copy_protect_bytes */
const char *read_mbr_copy_protect_bytes_explained(FILE *fp)
{
uint16_t t = read_mbr_copy_protect_bytes(fp);
switch(t)
{
case 0:
return _("not copy protected");
case 0x5a5a:
return _("copy protected");
default:
return _("unknown value");
}
} /* read_mbr_copy_protect_bytes_explained */
int is_br(FILE *fp)
{
/* A "file" is probably some kind of boot record if it contains the magic
chars 0x55, 0xAA at position 0x1FE */
unsigned char aucRef[] = {0x55, 0xAA};
return contains_data(fp, 0x1FE, aucRef, sizeof(aucRef));
} /* is_br */
int is_lilo_br(FILE *fp)
{
/* A "file" is probably a LILO boot record if it contains the magic
chars LILO at position 0x6 or 0x2 for floppies */
unsigned char aucRef[] = {'L','I','L','O'};
return ( contains_data(fp, 0x6, aucRef, sizeof(aucRef)) ||
contains_data(fp, 0x2, aucRef, sizeof(aucRef)) );
} /* is_lilo_br */
int is_dos_mbr(FILE *fp)
{
#include "mbr_dos.h"
return
contains_data(fp, 0x0, mbr_dos_0x0, sizeof(mbr_dos_0x0)) &&
is_br(fp);
} /* is_dos_mbr */
int is_dos_f2_mbr(FILE *fp)
{
#include "mbr_dos_f2.h"
return
contains_data(fp, 0x0, mbr_dos_f2_0x0, sizeof(mbr_dos_f2_0x0)) &&
is_br(fp);
} /* is_dos_f2_mbr */
int is_95b_mbr(FILE *fp)
{
#include "mbr_95b.h"
return
contains_data(fp, 0x0, mbr_95b_0x0, sizeof(mbr_95b_0x0)) &&
contains_data(fp, 0x0e0, mbr_95b_0x0e0, sizeof(mbr_95b_0x0e0)) &&
is_br(fp);
} /* is_95b_mbr */
int is_2000_mbr(FILE *fp)
{
#include "mbr_2000.h"
return
contains_data(fp, 0x0, mbr_2000_0x0, MBR_2000_LANG_INDEP_LEN) &&
is_br(fp);
} /* is_2000_mbr */
int is_vista_mbr(FILE *fp)
{
#include "mbr_vista.h"
return
contains_data(fp, 0x0, mbr_vista_0x0, MBR_VISTA_LANG_INDEP_LEN) &&
is_br(fp);
} /* is_vista_mbr */
int is_win7_mbr(FILE *fp)
{
#include "mbr_win7.h"
return
contains_data(fp, 0x0, mbr_win7_0x0, MBR_WIN7_LANG_INDEP_LEN) &&
is_br(fp);
} /* is_win7_mbr */
int is_rufus_mbr(FILE *fp)
{
#include "mbr_rufus.h"
return
contains_data(fp, 0x0, mbr_rufus_0x0, sizeof(mbr_rufus_0x0)) &&
is_br(fp);
} /* is_rufus_mbr */
int is_rufus_msg_mbr(FILE *fp)
{
#include "mbr_msg_rufus.h"
return
contains_data(fp, 0x0, mbr_msg_rufus_0x0, sizeof(mbr_msg_rufus_0x0)) &&
is_br(fp);
} /* is_rufus_msg_mbr */
int is_reactos_mbr(FILE *fp)
{
#include "mbr_reactos.h"
return
contains_data(fp, 0x0, mbr_reactos_0x0, sizeof(mbr_reactos_0x0)) &&
is_br(fp);
} /* is_reactos_mbr */
int is_grub4dos_mbr(FILE *fp)
{
#include "mbr_grub.h"
return
contains_data(fp, 0x0, mbr_grub_0x0, sizeof(mbr_grub_0x0)) &&
is_br(fp);
} /* is_grub_mbr */
int is_grub2_mbr(FILE *fp)
{
#include "mbr_grub2.h"
return
contains_data(fp, 0x0, mbr_grub2_0x0, sizeof(mbr_grub2_0x0)) &&
is_br(fp);
} /* is_grub2_mbr */
int is_kolibrios_mbr(FILE *fp)
{
#include "mbr_kolibri.h"
return
contains_data(fp, 0x0, mbr_kolibri_0x0, sizeof(mbr_kolibri_0x0)) &&
is_br(fp);
} /* is_kolibri_mbr */
int is_syslinux_mbr(FILE *fp)
{
#include "mbr_syslinux.h"
return
contains_data(fp, 0x0, mbr_syslinux_0x0, sizeof(mbr_syslinux_0x0)) &&
is_br(fp);
} /* is_syslinux_mbr */
int is_syslinux_gpt_mbr(FILE *fp)
{
#include "mbr_gpt_syslinux.h"
return
contains_data(fp, 0x0, mbr_gpt_syslinux_0x0,
sizeof(mbr_gpt_syslinux_0x0)) &&
is_br(fp);
} /* is_syslinux_gpt_mbr */
int is_zero_mbr(FILE *fp)
{
#include "mbr_zero.h"
return
contains_data(fp, 0x0, mbr_zero_0x0, sizeof(mbr_zero_0x0));
/* Don't bother to check 55AA signature */
} /* is_zero_mbr */
int is_zero_mbr_not_including_disk_signature_or_copy_protect(FILE *fp)
{
#include "mbr_zero.h"
return
contains_data(fp, 0x0, mbr_zero_0x0, 0x1b8);
} /* is_zero_mbr_not_including_disk_signature_or_copy_protect */
/* Handle nonstandard sector sizes (such as 4K) by writing
the boot marker at every 512-2 bytes location */
static int write_bootmark(FILE *fp)
{
unsigned char aucRef[] = {0x55, 0xAA};
unsigned long pos = 0x1FE;
for (pos = 0x1FE; pos < ulBytesPerSector; pos += 0x200) {
if (!write_data(fp, pos, aucRef, sizeof(aucRef)))
return 0;
}
return 1;
}
int write_dos_mbr(FILE *fp)
{
#include "mbr_dos.h"
return
write_data(fp, 0x0, mbr_dos_0x0, sizeof(mbr_dos_0x0)) &&
write_bootmark(fp);
} /* write_dos_mbr */
int write_95b_mbr(FILE *fp)
{
#include "mbr_95b.h"
return
write_data(fp, 0x0, mbr_95b_0x0, sizeof(mbr_95b_0x0)) &&
write_data(fp, 0x0e0, mbr_95b_0x0e0, sizeof(mbr_95b_0x0e0)) &&
write_bootmark(fp);
} /* write_95b_mbr */
int write_2000_mbr(FILE *fp)
{
#include "mbr_2000.h"
return
write_data(fp, 0x0, mbr_2000_0x0, sizeof(mbr_2000_0x0)) &&
write_bootmark(fp);
} /* write_2000_mbr */
int write_vista_mbr(FILE *fp)
{
#include "mbr_vista.h"
return
write_data(fp, 0x0, mbr_vista_0x0, sizeof(mbr_vista_0x0)) &&
write_bootmark(fp);
} /* write_vista_mbr */
int write_win7_mbr(FILE *fp)
{
#include "mbr_win7.h"
return
write_data(fp, 0x0, mbr_win7_0x0, sizeof(mbr_win7_0x0)) &&
write_bootmark(fp);
} /* write_win7_mbr */
int write_rufus_mbr(FILE *fp)
{
#include "mbr_rufus.h"
return
write_data(fp, 0x0, mbr_rufus_0x0, sizeof(mbr_rufus_0x0)) &&
write_bootmark(fp);
} /* write_rufus_mbr */
int write_rufus_msg_mbr(FILE *fp)
{
#include "mbr_msg_rufus.h"
return
write_data(fp, 0x0, mbr_msg_rufus_0x0, sizeof(mbr_msg_rufus_0x0)) &&
write_bootmark(fp);
} /* write_rufus_msg_mbr */
int write_reactos_mbr(FILE *fp)
{
#include "mbr_reactos.h"
return
write_data(fp, 0x0, mbr_reactos_0x0, sizeof(mbr_reactos_0x0)) &&
write_bootmark(fp);
} /* write_reactos_mbr */
int write_kolibrios_mbr(FILE *fp)
{
#include "mbr_kolibri.h"
return
write_data(fp, 0x0, mbr_kolibri_0x0, sizeof(mbr_kolibri_0x0)) &&
write_bootmark(fp);
} /* write_kolibri_mbr */
int write_syslinux_mbr(FILE *fp)
{
#include "mbr_syslinux.h"
return
write_data(fp, 0x0, mbr_syslinux_0x0, sizeof(mbr_syslinux_0x0)) &&
write_bootmark(fp);
} /* write_syslinux_mbr */
int write_syslinux_gpt_mbr(FILE *fp)
{
#include "mbr_gpt_syslinux.h"
return
write_data(fp, 0x0, mbr_gpt_syslinux_0x0, sizeof(mbr_gpt_syslinux_0x0)) &&
write_bootmark(fp);
} /* write_syslinux_gpt_mbr */
int write_grub4dos_mbr(FILE *fp)
{
#include "mbr_grub.h"
return
write_data(fp, 0x0, mbr_grub_0x0, sizeof(mbr_grub_0x0)) &&
write_bootmark(fp);
}
int write_grub2_mbr(FILE *fp)
{
#include "mbr_grub2.h"
return
write_data(fp, 0x0, mbr_grub2_0x0, sizeof(mbr_grub2_0x0)) &&
write_bootmark(fp);
}
int write_zero_mbr(FILE *fp)
{
#include "mbr_zero.h"
return
write_data(fp, 0x0, mbr_zero_0x0, sizeof(mbr_zero_0x0)) &&
write_bootmark(fp);
} /* write_zero_mbr */
| 8,726 |
C
|
.c
| 295 | 25.810169 | 80 | 0.645601 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,790 |
fat32.c
|
pbatard_rufus/src/ms-sys/fat32.c
|
/******************************************************************
Copyright (C) 2009 Henrik Carlqvist
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., 675 Mass Ave, Cambridge, MA 02139, USA.
******************************************************************/
#include <stdio.h>
#include <string.h>
#include "file.h"
#include "fat32.h"
int is_fat_32_fs(FILE *fp)
{
char *szMagic = "FAT32 ";
return contains_data(fp, 0x52, szMagic, strlen(szMagic));
} /* is_fat_32_fs */
int is_fat_32_br(FILE *fp)
{
/* A "file" is probably some kind of FAT32 boot record if it contains the
magic chars 0x55, 0xAA at positions 0x1FE, 0x3FE and 0x5FE */
unsigned char aucRef[] = {0x55, 0xAA};
unsigned char aucMagic[] = {'M','S','W','I','N','4','.','1'};
int i;
for(i=0 ; i<3 ; i++)
if( ! contains_data(fp, 0x1FEULL + i * 0x200ULL, aucRef, sizeof(aucRef)))
return 0;
if( ! contains_data(fp, 0x03, aucMagic, sizeof(aucMagic)))
return 0;
return 1;
} /* is_fat_32_br */
int entire_fat_32_br_matches(FILE *fp)
{
#include "br_fat32_0x0.h"
#include "br_fat32_0x52.h"
#include "br_fat32_0x3f0.h"
return
( contains_data(fp, 0x0, br_fat32_0x0, sizeof(br_fat32_0x0)) &&
/* BIOS Parameter Block might differ between systems */
contains_data(fp, 0x52, br_fat32_0x52, sizeof(br_fat32_0x52)) &&
/* Cluster information might differ between systems */
contains_data(fp, 0x3f0, br_fat32_0x3f0, sizeof(br_fat32_0x3f0)) );
} /* entire_fat_32_br_matches */
int write_fat_32_br(FILE *fp, int bKeepLabel)
{
#include "label_11_char.h"
#include "br_fat32_0x0.h"
#include "br_fat32_0x52.h"
#include "br_fat32_0x3f0.h"
if(bKeepLabel)
return
( write_data(fp, 0x0, br_fat32_0x0, sizeof(br_fat32_0x0)) &&
/* BIOS Parameter Block should not be overwritten */
write_data(fp, 0x52, br_fat32_0x52, sizeof(br_fat32_0x52)) &&
/* Cluster information is not overwritten, however, it would be OK
to write 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff here. */
write_data(fp, 0x3f0, br_fat32_0x3f0, sizeof(br_fat32_0x3f0)) );
else
return
( write_data(fp, 0x0, br_fat32_0x0, sizeof(br_fat32_0x0)) &&
/* BIOS Parameter Block should not be overwritten */
write_data(fp, 0x47, label_11_char, sizeof(label_11_char)) &&
write_data(fp, 0x52, br_fat32_0x52, sizeof(br_fat32_0x52)) &&
/* Cluster information is not overwritten, however, it would be OK
to write 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff here. */
write_data(fp, 0x3f0, br_fat32_0x3f0, sizeof(br_fat32_0x3f0)) );
} /* write_fat_32_br */
int entire_fat_32_fd_br_matches(FILE *fp)
{
#include "br_fat32_0x0.h"
#include "br_fat32fd_0x52.h"
#include "br_fat32fd_0x3f0.h"
return
( contains_data(fp, 0x0, br_fat32_0x0, sizeof(br_fat32_0x0)) &&
/* BIOS Parameter Block might differ between systems */
contains_data(fp, 0x52, br_fat32_0x52, sizeof(br_fat32_0x52)) &&
/* Cluster information might differ between systems */
contains_data(fp, 0x3f0, br_fat32_0x3f0, sizeof(br_fat32_0x3f0)) );
} /* entire_fat_32_fd_br_matches */
int write_fat_32_fd_br(FILE *fp, int bKeepLabel)
{
#include "label_11_char.h"
#include "br_fat32_0x0.h"
#include "br_fat32fd_0x52.h"
#include "br_fat32fd_0x3f0.h"
if(bKeepLabel)
return
( write_data(fp, 0x0, br_fat32_0x0, sizeof(br_fat32_0x0)) &&
/* BIOS Parameter Block should not be overwritten */
write_data(fp, 0x52, br_fat32_0x52, sizeof(br_fat32_0x52)) &&
/* Cluster information is not overwritten, however, it would be OK
to write 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff here. */
write_data(fp, 0x3f0, br_fat32_0x3f0, sizeof(br_fat32_0x3f0)) );
else
return
( write_data(fp, 0x0, br_fat32_0x0, sizeof(br_fat32_0x0)) &&
/* BIOS Parameter Block should not be overwritten */
write_data(fp, 0x47, label_11_char, sizeof(label_11_char)) &&
write_data(fp, 0x52, br_fat32_0x52, sizeof(br_fat32_0x52)) &&
/* Cluster information is not overwritten, however, it would be OK
to write 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff here. */
write_data(fp, 0x3f0, br_fat32_0x3f0, sizeof(br_fat32_0x3f0)) );
} /* write_fat_32_fd_br */
int entire_fat_32_nt_br_matches(FILE *fp)
{
#include "br_fat32_0x0.h"
#include "br_fat32nt_0x52.h"
#include "br_fat32nt_0x3f0.h"
#include "br_fat32nt_0x1800.h"
return
( contains_data(fp, 0x0, br_fat32_0x0, sizeof(br_fat32_0x0)) &&
/* BIOS Parameter Block might differ between systems */
contains_data(fp, 0x52, br_fat32nt_0x52, sizeof(br_fat32nt_0x52)) &&
/* Cluster information might differ between systems */
contains_data(fp, 0x3f0, br_fat32nt_0x3f0, sizeof(br_fat32nt_0x3f0)) &&
contains_data(fp, 0x1800, br_fat32nt_0x1800, sizeof(br_fat32nt_0x1800))
);
} /* entire_fat_32_nt_br_matches */
int write_fat_32_nt_br(FILE *fp, int bKeepLabel)
{
#include "label_11_char.h"
#include "br_fat32_0x0.h"
#include "br_fat32nt_0x52.h"
#include "br_fat32nt_0x3f0.h"
#include "br_fat32nt_0x1800.h"
if(bKeepLabel)
return
( write_data(fp, 0x0, br_fat32_0x0, sizeof(br_fat32_0x0)) &&
/* BIOS Parameter Block should not be overwritten */
write_data(fp, 0x52, br_fat32nt_0x52, sizeof(br_fat32nt_0x52)) &&
/* Cluster information is not overwritten, however, it would be OK
to write 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff here. */
write_data(fp, 0x3f0, br_fat32nt_0x3f0, sizeof(br_fat32nt_0x3f0)) &&
write_data(fp, 0x1800, br_fat32nt_0x1800, sizeof(br_fat32nt_0x1800))
);
else
return
( write_data(fp, 0x0, br_fat32_0x0, sizeof(br_fat32_0x0)) &&
/* BIOS Parameter Block should not be overwritten */
write_data(fp, 0x47, label_11_char, sizeof(label_11_char)) &&
write_data(fp, 0x52, br_fat32nt_0x52, sizeof(br_fat32nt_0x52)) &&
/* Cluster information is not overwritten, however, it would be OK
to write 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff here. */
write_data(fp, 0x3f0, br_fat32nt_0x3f0, sizeof(br_fat32nt_0x3f0)) &&
write_data(fp, 0x1800, br_fat32nt_0x1800, sizeof(br_fat32nt_0x1800))
);
} /* write_fat_32_nt_br */
int entire_fat_32_pe_br_matches(FILE *fp)
{
#include "br_fat32_0x0.h"
#include "br_fat32pe_0x52.h"
#include "br_fat32pe_0x3f0.h"
#include "br_fat32pe_0x1800.h"
return
( contains_data(fp, 0x0, br_fat32_0x0, sizeof(br_fat32_0x0)) &&
/* BIOS Parameter Block might differ between systems */
contains_data(fp, 0x52, br_fat32pe_0x52, sizeof(br_fat32pe_0x52)) &&
/* Cluster information might differ between systems */
contains_data(fp, 0x3f0, br_fat32pe_0x3f0, sizeof(br_fat32pe_0x3f0)) &&
contains_data(fp, 0x1800, br_fat32pe_0x1800, sizeof(br_fat32pe_0x1800))
);
} /* entire_fat_32_nt_br_matches */
int write_fat_32_pe_br(FILE *fp, int bKeepLabel)
{
#include "label_11_char.h"
#include "br_fat32_0x0.h"
#include "br_fat32pe_0x52.h"
#include "br_fat32pe_0x3f0.h"
#include "br_fat32pe_0x1800.h"
if(bKeepLabel)
return
( write_data(fp, 0x0, br_fat32_0x0, sizeof(br_fat32_0x0)) &&
/* BIOS Parameter Block should not be overwritten */
write_data(fp, 0x52, br_fat32pe_0x52, sizeof(br_fat32pe_0x52)) &&
/* Cluster information is not overwritten, however, it would bo OK
to write 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff here. */
write_data(fp, 0x3f0, br_fat32pe_0x3f0, sizeof(br_fat32pe_0x3f0)) &&
write_data(fp, 0x1800, br_fat32pe_0x1800, sizeof(br_fat32pe_0x1800))
);
else
return
( write_data(fp, 0x0, br_fat32_0x0, sizeof(br_fat32_0x0)) &&
/* BIOS Parameter Block should not be overwritten */
write_data(fp, 0x47, label_11_char, sizeof(label_11_char)) &&
write_data(fp, 0x52, br_fat32pe_0x52, sizeof(br_fat32pe_0x52)) &&
/* Cluster information is not overwritten, however, it would bo OK
to write 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff here. */
write_data(fp, 0x3f0, br_fat32pe_0x3f0, sizeof(br_fat32pe_0x3f0)) &&
write_data(fp, 0x1800, br_fat32pe_0x1800, sizeof(br_fat32pe_0x1800))
);
} /* write_fat_32_pe_br */
int entire_fat_32_ros_br_matches(FILE *fp)
{
#include "br_fat32_0x0.h"
#include "br_fat32ros_0x52.h"
#include "br_fat32ros_0x3f0.h"
#include "br_fat32ros_0x1c00.h"
return
( contains_data(fp, 0x0, br_fat32_0x0, sizeof(br_fat32_0x0)) &&
/* BIOS Parameter Block might differ between systems */
contains_data(fp, 0x52, br_fat32ros_0x52, sizeof(br_fat32ros_0x52)) &&
/* Cluster information might differ between systems */
contains_data(fp, 0x3f0, br_fat32ros_0x3f0, sizeof(br_fat32ros_0x3f0)) &&
contains_data(fp, 0x1c00, br_fat32ros_0x1c00, sizeof(br_fat32ros_0x1c00))
);
} /* entire_fat_32_ros_br_matches */
/* See http://doxygen.reactos.org/dc/d83/bootsup_8c_source.html#l01596 */
int write_fat_32_ros_br(FILE *fp, int bKeepLabel)
{
#include "label_11_char.h"
#include "br_fat32_0x0.h"
#include "br_fat32ros_0x52.h"
#include "br_fat32ros_0x3f0.h"
#include "br_fat32ros_0x1c00.h"
if(bKeepLabel)
return
( write_data(fp, 0x0, br_fat32_0x0, sizeof(br_fat32_0x0)) &&
/* BIOS Parameter Block should not be overwritten */
write_data(fp, 0x52, br_fat32ros_0x52, sizeof(br_fat32ros_0x52)) &&
/* Cluster information is not overwritten, however, it would be OK
to write 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff here. */
write_data(fp, 0x3f0, br_fat32ros_0x3f0, sizeof(br_fat32ros_0x3f0)) &&
write_data(fp, 0x1c00, br_fat32ros_0x1c00, sizeof(br_fat32ros_0x1c00))
);
else
return
( write_data(fp, 0x0, br_fat32_0x0, sizeof(br_fat32_0x0)) &&
/* BIOS Parameter Block should not be overwritten */
write_data(fp, 0x47, label_11_char, sizeof(label_11_char)) &&
write_data(fp, 0x52, br_fat32ros_0x52, sizeof(br_fat32ros_0x52)) &&
/* Cluster information is not overwritten, however, it would be OK
to write 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff here. */
write_data(fp, 0x3f0, br_fat32ros_0x3f0, sizeof(br_fat32ros_0x3f0)) &&
write_data(fp, 0x1c00, br_fat32ros_0x1c00, sizeof(br_fat32ros_0x1c00))
);
} /* write_fat_32_ros_br */
int entire_fat_32_kos_br_matches(FILE *fp)
{
#include "br_fat32_0x0.h"
#include "br_fat32kos_0x52.h"
return
( contains_data(fp, 0x0, br_fat32_0x0, sizeof(br_fat32_0x0)) &&
contains_data(fp, 0x52, br_fat32kos_0x52, sizeof(br_fat32kos_0x52)) );
} /* entire_fat_32_kos_br_matches */
int write_fat_32_kos_br(FILE *fp, int bKeepLabel)
{
#include "label_11_char.h"
#include "br_fat32_0x0.h"
#include "br_fat32kos_0x52.h"
if(bKeepLabel)
return
( write_data(fp, 0x0, br_fat32_0x0, sizeof(br_fat32_0x0)) &&
write_data(fp, 0x52, br_fat32kos_0x52, sizeof(br_fat32kos_0x52)) );
else
return
( write_data(fp, 0x0, br_fat32_0x0, sizeof(br_fat32_0x0)) &&
write_data(fp, 0x47, label_11_char, sizeof(label_11_char)) &&
write_data(fp, 0x52, br_fat32kos_0x52, sizeof(br_fat32kos_0x52)) );
} /* write_fat_32_kos_br */
| 11,597 |
C
|
.c
| 265 | 39.773585 | 79 | 0.680088 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,791 |
file.c
|
pbatard_rufus/src/ms-sys/file.c
|
/******************************************************************
Copyright (C) 2009 Henrik Carlqvist
Modified for Rufus/Windows (C) 2011-2019 Pete Batard
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., 675 Mass Ave, Cambridge, MA 02139, USA.
******************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include "../rufus.h"
#include "file.h"
extern unsigned long ulBytesPerSector;
/* Returns the number of bytes written or -1 on error */
int64_t write_sectors(HANDLE hDrive, uint64_t SectorSize,
uint64_t StartSector, uint64_t nSectors,
const void *pBuf)
{
LARGE_INTEGER ptr;
DWORD Size;
if((nSectors*SectorSize) > 0xFFFFFFFFUL)
{
uprintf("write_sectors: nSectors x SectorSize is too big\n");
return -1;
}
Size = (DWORD)(nSectors*SectorSize);
ptr.QuadPart = StartSector*SectorSize;
if(!SetFilePointerEx(hDrive, ptr, NULL, FILE_BEGIN))
{
uprintf("write_sectors: Could not access sector 0x%08" PRIx64 " - %s\n", StartSector, WindowsErrorString());
return -1;
}
LastWriteError = 0;
if(!WriteFileWithRetry(hDrive, pBuf, Size, &Size, WRITE_RETRIES))
{
LastWriteError = RUFUS_ERROR(GetLastError());
uprintf("write_sectors: Write error %s\n", WindowsErrorString());
uprintf(" StartSector: 0x%08" PRIx64 ", nSectors: 0x%" PRIx64 ", SectorSize: 0x%" PRIx64 "\n", StartSector, nSectors, SectorSize);
return -1;
}
if (Size != nSectors*SectorSize)
{
/* Some large drives return 0, even though all the data was written - See github #787 */
if (large_drive && Size == 0) {
uprintf("Warning: Possible short write\n");
return 0;
}
uprintf("write_sectors: Write error\n");
LastWriteError = RUFUS_ERROR(ERROR_WRITE_FAULT);
uprintf(" Wrote: %d, Expected: %" PRIu64 "\n", Size, nSectors*SectorSize);
uprintf(" StartSector: 0x%08" PRIx64 ", nSectors: 0x%" PRIx64 ", SectorSize: 0x%" PRIx64 "\n", StartSector, nSectors, SectorSize);
return -1;
}
return (int64_t)Size;
}
/* Returns the number of bytes read or -1 on error */
int64_t read_sectors(HANDLE hDrive, uint64_t SectorSize,
uint64_t StartSector, uint64_t nSectors,
void *pBuf)
{
LARGE_INTEGER ptr;
DWORD Size;
if((nSectors*SectorSize) > 0xFFFFFFFFUL)
{
uprintf("read_sectors: nSectors x SectorSize is too big\n");
return -1;
}
Size = (DWORD)(nSectors*SectorSize);
ptr.QuadPart = StartSector*SectorSize;
if(!SetFilePointerEx(hDrive, ptr, NULL, FILE_BEGIN))
{
uprintf("read_sectors: Could not access sector 0x%08" PRIx64 " - %s\n", StartSector, WindowsErrorString());
return -1;
}
if((!ReadFile(hDrive, pBuf, Size, &Size, NULL)) || (Size != nSectors*SectorSize))
{
uprintf("read_sectors: Read error %s\n", (GetLastError()!=ERROR_SUCCESS)?WindowsErrorString():"");
uprintf(" Read: %d, Expected: %" PRIu64 "\n", Size, nSectors*SectorSize);
uprintf(" StartSector: 0x%08" PRIx64 ", nSectors: 0x%" PRIx64 ", SectorSize: 0x%" PRIx64 "\n", StartSector, nSectors, SectorSize);
}
return (int64_t)Size;
}
/*
* The following calls use a hijacked fp on Windows that contains:
* fp->_handle: a Windows handle
* fp->_offset: a file offset
*/
int contains_data(FILE *fp, uint64_t Position,
const void *pData, uint64_t Len)
{
int r = 0;
unsigned char *aucBuf = _mm_malloc(MAX_DATA_LEN, 16);
if(aucBuf == NULL)
return 0;
if(!read_data(fp, Position, aucBuf, Len))
goto out;
if(memcmp(pData, aucBuf, (size_t)Len))
goto out;
r = 1;
out:
_mm_free(aucBuf);
return r;
} /* contains_data */
int read_data(FILE *fp, uint64_t Position,
void *pData, uint64_t Len)
{
int r = 0;
unsigned char *aucBuf = _mm_malloc(MAX_DATA_LEN, 16);
FAKE_FD* fd = (FAKE_FD*)fp;
HANDLE hDrive = (HANDLE)fd->_handle;
uint64_t StartSector, EndSector, NumSectors;
if (aucBuf == NULL)
return 0;
Position += fd->_offset;
StartSector = Position/ulBytesPerSector;
EndSector = (Position+Len+ulBytesPerSector -1)/ulBytesPerSector;
NumSectors = (size_t)(EndSector - StartSector);
if((NumSectors*ulBytesPerSector) > MAX_DATA_LEN)
{
uprintf("read_data: Please increase MAX_DATA_LEN in file.h\n");
goto out;
}
if(Len > 0xFFFFFFFFUL)
{
uprintf("read_data: Len is too big\n");
goto out;
}
if(read_sectors(hDrive, ulBytesPerSector, StartSector,
NumSectors, aucBuf) <= 0)
goto out;
memcpy(pData, &aucBuf[Position - StartSector*ulBytesPerSector], (size_t)Len);
r = 1;
out:
_mm_free(aucBuf);
return r;
} /* read_data */
/* May read/write the same sector many times, but compatible with existing ms-sys */
int write_data(FILE *fp, uint64_t Position,
const void *pData, uint64_t Len)
{
int r = 0;
/* Windows' WriteFile() may require a buffer that is aligned to the sector size */
unsigned char *aucBuf = _mm_malloc(MAX_DATA_LEN, 4096);
FAKE_FD* fd = (FAKE_FD*)fp;
HANDLE hDrive = (HANDLE)fd->_handle;
uint64_t StartSector, EndSector, NumSectors;
if (aucBuf == NULL)
return 0;
Position += fd->_offset;
StartSector = Position/ulBytesPerSector;
EndSector = (Position+Len+ulBytesPerSector-1)/ulBytesPerSector;
NumSectors = EndSector - StartSector;
if((NumSectors*ulBytesPerSector) > MAX_DATA_LEN)
{
uprintf("write_data: Please increase MAX_DATA_LEN in file.h\n");
goto out;
}
if(Len > 0xFFFFFFFFUL)
{
uprintf("write_data: Len is too big\n");
goto out;
}
/* Data to write may not be aligned on a sector boundary => read into a sector buffer first */
if(read_sectors(hDrive, ulBytesPerSector, StartSector,
NumSectors, aucBuf) <= 0)
goto out;
if(!memcpy(&aucBuf[Position - StartSector*ulBytesPerSector], pData, (size_t)Len))
goto out;
if(write_sectors(hDrive, ulBytesPerSector, StartSector,
NumSectors, aucBuf) <= 0)
goto out;
r = 1;
out:
_mm_free(aucBuf);
return r;
} /* write_data */
| 6,883 |
C
|
.c
| 184 | 32.146739 | 137 | 0.65009 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
4,792 |
partition_info.c
|
pbatard_rufus/src/ms-sys/partition_info.c
|
/******************************************************************
Copyright (C) 2009 Henrik Carlqvist
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., 675 Mass Ave, Cambridge, MA 02139, USA.
******************************************************************/
#include <stdio.h>
#include "file.h"
#include "partition_info.h"
int write_partition_number_of_heads(FILE *fp, int iHeads)
{
unsigned char aucBuf[2];
unsigned short s = (unsigned short) iHeads;
if(!s)
return 0;
/* Converting a number like this is not necessary as long as we are on
i386 compatible CPUs, however, the following code might make the program
more portable... */
aucBuf[0] = (unsigned char)(s & 0xff);
aucBuf[1] = (unsigned char)((s & 0xff00) >> 8);
return write_data(fp, 0x1a, aucBuf, 2);
} /* write_partition_number_of_heads */
int write_partition_start_sector_number(FILE *fp, int iStartSector)
{
unsigned char aucBuf[4];
unsigned long l = (unsigned long)iStartSector;
if(!l)
return 0;
/* Converting a number like this is not necessary as long as we are on
i386 compatible CPUs, however, the following code might make the program
more portable... */
aucBuf[0] = (unsigned char)(l & 0xff);
aucBuf[1] = (unsigned char)((l & 0xff00) >> 8);
aucBuf[2] = (unsigned char)((l & 0xff0000) >> 16);
aucBuf[3] = (unsigned char)((l & 0xff000000) >> 24);
return write_data(fp, 0x1c, aucBuf, 4);
} /* write_partition_start_sector_number */
int write_partition_physical_disk_drive_id_fat32(FILE *fp)
{
unsigned char ucId = 0x80; /* C: */
return write_data(fp, 0x40, &ucId, 1);
} /* write_partition_physical_disk_drive_id_fat32 */
int write_partition_physical_disk_drive_id_fat16(FILE *fp)
{
unsigned char ucId = 0x80; /* C: */
return write_data(fp, 0x24, &ucId, 1);
} /* write_partition_physical_disk_drive_id_fat16 */
| 2,505 |
C
|
.c
| 55 | 41.709091 | 78 | 0.66571 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,793 |
fat16.c
|
pbatard_rufus/src/ms-sys/fat16.c
|
/******************************************************************
Copyright (C) 2009 Henrik Carlqvist
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., 675 Mass Ave, Cambridge, MA 02139, USA.
******************************************************************/
#include <stdio.h>
#include <string.h>
#include "file.h"
#include "fat16.h"
int is_fat_16_fs(FILE *fp)
{
char *szMagic = "FAT16 ";
return contains_data(fp, 0x36, szMagic, strlen(szMagic));
} /* is_fat_16_fs */
int is_fat_16_br(FILE *fp)
{
/* A "file" is probably some kind of FAT16 boot record if it contains the
magic chars 0x55, 0xAA at positions 0x1FE */
unsigned char aucRef[] = {0x55, 0xAA};
unsigned char aucMagic[] = {'M','S','W','I','N','4','.','1'};
if( ! contains_data(fp, 0x1FE, aucRef, sizeof(aucRef)))
return 0;
if( ! contains_data(fp, 0x03, aucMagic, sizeof(aucMagic)))
return 0;
return 1;
} /* is_fat_16_br */
int entire_fat_16_br_matches(FILE *fp)
{
#include "br_fat16_0x0.h"
#include "br_fat16_0x3e.h"
return
( contains_data(fp, 0x0, br_fat16_0x0, sizeof(br_fat16_0x0)) &&
/* BIOS Parameter Block might differ between systems */
contains_data(fp, 0x3e, br_fat16_0x3e, sizeof(br_fat16_0x3e)) );
} /* entire_fat_16_br_matches */
int write_fat_16_br(FILE *fp, int bKeepLabel)
{
#include "label_11_char.h"
#include "br_fat16_0x0.h"
#include "br_fat16_0x3e.h"
if(bKeepLabel)
return
( write_data(fp, 0x0, br_fat16_0x0, sizeof(br_fat16_0x0)) &&
/* BIOS Parameter Block should not be overwritten */
write_data(fp, 0x3e, br_fat16_0x3e, sizeof(br_fat16_0x3e)) );
else
return
( write_data(fp, 0x0, br_fat16_0x0, sizeof(br_fat16_0x0)) &&
/* BIOS Parameter Block should not be overwritten */
write_data(fp, 0x2b, label_11_char, sizeof(label_11_char)) &&
write_data(fp, 0x3e, br_fat16_0x3e, sizeof(br_fat16_0x3e)) );
} /* write_fat_16_br */
int entire_fat_16_fd_br_matches(FILE *fp)
{
#include "br_fat16_0x0.h"
#include "br_fat16fd_0x3e.h"
return
( contains_data(fp, 0x0, br_fat16_0x0, sizeof(br_fat16_0x0)) &&
/* BIOS Parameter Block might differ between systems */
contains_data(fp, 0x3e, br_fat16_0x3e, sizeof(br_fat16_0x3e)) );
} /* entire_fat_16_fd_br_matches */
int write_fat_16_fd_br(FILE *fp, int bKeepLabel)
{
#include "label_11_char.h"
#include "br_fat16_0x0.h"
#include "br_fat16fd_0x3e.h"
if(bKeepLabel)
return
( write_data(fp, 0x0, br_fat16_0x0, sizeof(br_fat16_0x0)) &&
/* BIOS Parameter Block should not be overwritten */
write_data(fp, 0x3e, br_fat16_0x3e, sizeof(br_fat16_0x3e)) );
else
return
( write_data(fp, 0x0, br_fat16_0x0, sizeof(br_fat16_0x0)) &&
/* BIOS Parameter Block should not be overwritten */
write_data(fp, 0x2b, label_11_char, sizeof(label_11_char)) &&
write_data(fp, 0x3e, br_fat16_0x3e, sizeof(br_fat16_0x3e)) );
} /* write_fat_16_fd_br */
int entire_fat_16_ros_br_matches(FILE *fp)
{
#include "br_fat16ros_0x0.h"
#include "br_fat16ros_0x3e.h"
return
( contains_data(fp, 0x0, br_fat16_0x0, sizeof(br_fat16_0x0)) &&
/* BIOS Parameter Block might differ between systems */
contains_data(fp, 0x3e, br_fat16_0x3e, sizeof(br_fat16_0x3e)) );
} /* entire_fat_16_ros_br_matches */
int write_fat_16_ros_br(FILE *fp, int bKeepLabel)
{
#include "label_11_char.h"
#include "br_fat16ros_0x0.h"
#include "br_fat16ros_0x3e.h"
if(bKeepLabel)
return
( write_data(fp, 0x0, br_fat16_0x0, sizeof(br_fat16_0x0)) &&
/* BIOS Parameter Block should not be overwritten */
write_data(fp, 0x3e, br_fat16_0x3e, sizeof(br_fat16_0x3e)) );
else
return
( write_data(fp, 0x0, br_fat16_0x0, sizeof(br_fat16_0x0)) &&
/* BIOS Parameter Block should not be overwritten */
write_data(fp, 0x2b, label_11_char, sizeof(label_11_char)) &&
write_data(fp, 0x3e, br_fat16_0x3e, sizeof(br_fat16_0x3e)) );
} /* write_fat_16_ros_br */
| 4,579 |
C
|
.c
| 113 | 36.690265 | 76 | 0.659019 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,794 |
br_fat32ros_0x1c00.h
|
pbatard_rufus/src/ms-sys/inc/br_fat32ros_0x1c00.h
|
unsigned char br_fat32ros_0x1c00[] = {
0x66, 0x8b, 0x86, 0x2c, 0x00, 0x66, 0x3d, 0xf8, 0xff, 0xff, 0x0f, 0x72,
0x03, 0xe9, 0x6c, 0x01, 0xbb, 0x00, 0x20, 0x8e, 0xc3, 0xe8, 0x26, 0x01,
0x31, 0xdb, 0x8a, 0x9e, 0x0d, 0x00, 0xc1, 0xe3, 0x04, 0xb8, 0x00, 0x20,
0x8e, 0xc0, 0x31, 0xff, 0xbe, 0xa3, 0x7f, 0xb9, 0x0b, 0x00, 0xf3, 0xa6,
0x74, 0x2b, 0x4b, 0x75, 0x03, 0xe9, 0x44, 0x01, 0x8c, 0xc0, 0x83, 0xc0,
0x02, 0x8e, 0xc0, 0x31, 0xff, 0xbe, 0xa3, 0x7f, 0xb9, 0x0b, 0x00, 0xf3,
0xa6, 0x74, 0x12, 0x4b, 0x75, 0xea, 0x66, 0x8b, 0x86, 0x2c, 0x00, 0xe8,
0x6c, 0x00, 0x66, 0x89, 0x86, 0x2c, 0x00, 0xeb, 0xa3, 0xbe, 0xae, 0x7f,
0xe8, 0x42, 0xff, 0x31, 0xff, 0x31, 0xd2, 0x26, 0x8b, 0x45, 0x14, 0x66,
0xc1, 0xe0, 0x10, 0x26, 0x8b, 0x45, 0x1a, 0x66, 0x83, 0xf8, 0x02, 0x73,
0x03, 0xe9, 0x17, 0xff, 0x66, 0x3d, 0xf8, 0xff, 0xff, 0x0f, 0x72, 0x03,
0xe9, 0x0c, 0xff, 0xbb, 0x80, 0x0f, 0x8e, 0xc3, 0x66, 0x3d, 0xf8, 0xff,
0xff, 0x0f, 0x73, 0x21, 0x66, 0x50, 0x31, 0xdb, 0x06, 0xe8, 0xa2, 0x00,
0x07, 0x31, 0xdb, 0x8a, 0x9e, 0x0d, 0x00, 0xc1, 0xe3, 0x05, 0x8c, 0xc0,
0x01, 0xd8, 0x8e, 0xc0, 0x66, 0x58, 0x06, 0xe8, 0x10, 0x00, 0x07, 0xeb,
0xd7, 0x8a, 0x96, 0x40, 0x00, 0x8a, 0x36, 0xfd, 0x7d, 0xea, 0x00, 0xf8,
0x00, 0x00, 0x66, 0xc1, 0xe0, 0x02, 0x66, 0x89, 0xc1, 0x66, 0x31, 0xd2,
0x66, 0x0f, 0xb7, 0x9e, 0x0b, 0x00, 0x66, 0x53, 0x66, 0xf7, 0xf3, 0x66,
0x0f, 0xb7, 0x9e, 0x0e, 0x00, 0x66, 0x01, 0xd8, 0x66, 0x8b, 0x9e, 0x1c,
0x00, 0x66, 0x01, 0xd8, 0x66, 0x5b, 0x66, 0x4b, 0x66, 0x21, 0xd9, 0x66,
0x0f, 0xb7, 0x9e, 0x28, 0x00, 0x83, 0xe3, 0x0f, 0x74, 0x18, 0x3a, 0x9e,
0x10, 0x00, 0x72, 0x03, 0xe9, 0x90, 0xfe, 0x66, 0x50, 0x66, 0x8b, 0x86,
0x24, 0x00, 0x66, 0xf7, 0xe3, 0x66, 0x5a, 0x66, 0x01, 0xd0, 0x66, 0x51,
0xbb, 0x00, 0x90, 0x8e, 0xc3, 0x66, 0x3b, 0x06, 0x3a, 0x7f, 0x74, 0x0c,
0x66, 0xa3, 0x3a, 0x7f, 0x31, 0xdb, 0xb9, 0x01, 0x00, 0xe8, 0xaf, 0xfd,
0x66, 0x59, 0x26, 0x67, 0x66, 0x8b, 0x01, 0x66, 0x25, 0xff, 0xff, 0xff,
0x0f, 0xc3, 0xff, 0xff, 0xff, 0xff, 0x66, 0x48, 0x66, 0x48, 0x66, 0x31,
0xd2, 0x66, 0x0f, 0xb6, 0x9e, 0x0d, 0x00, 0x66, 0xf7, 0xe3, 0x66, 0x50,
0x66, 0x31, 0xd2, 0x66, 0x0f, 0xb6, 0x86, 0x10, 0x00, 0x66, 0xf7, 0xa6,
0x24, 0x00, 0x66, 0x0f, 0xb7, 0x9e, 0x0e, 0x00, 0x66, 0x01, 0xd8, 0x66,
0x03, 0x86, 0x1c, 0x00, 0x66, 0x5b, 0x66, 0x01, 0xd8, 0x31, 0xdb, 0x0f,
0xb6, 0x8e, 0x0d, 0x00, 0xe8, 0x60, 0xfd, 0xc3, 0xbe, 0x8b, 0x7f, 0xe8,
0x23, 0xfe, 0xbe, 0xd9, 0x7d, 0xe8, 0x1d, 0xfe, 0xe9, 0x0e, 0xfe, 0x66,
0x72, 0x65, 0x65, 0x6c, 0x64, 0x72, 0x2e, 0x73, 0x79, 0x73, 0x20, 0x6e,
0x6f, 0x74, 0x20, 0x66, 0x6f, 0x75, 0x6e, 0x64, 0x0d, 0x0a, 0x00, 0x46,
0x52, 0x45, 0x45, 0x4c, 0x44, 0x52, 0x20, 0x53, 0x59, 0x53, 0x4c, 0x6f,
0x61, 0x64, 0x69, 0x6e, 0x67, 0x20, 0x46, 0x72, 0x65, 0x65, 0x4c, 0x6f,
0x61, 0x64, 0x65, 0x72, 0x2e, 0x2e, 0x2e, 0x0d, 0x0a, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0xaa
};
| 3,156 |
C
|
.c
| 45 | 68.177778 | 72 | 0.66731 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,795 |
label_11_char.h
|
pbatard_rufus/src/ms-sys/inc/label_11_char.h
|
unsigned char label_11_char[] = {'N','O',' ','N','A','M','E',' ',' ',' ',' '};
| 79 |
C
|
.c
| 1 | 78 | 78 | 0.371795 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,796 |
mbr_reactos.h
|
pbatard_rufus/src/ms-sys/inc/mbr_reactos.h
|
/* First 267 bytes of MBR from ReactOS */
unsigned char mbr_reactos_0x0[] = {
0xfa, 0xfc, 0x31, 0xc0, 0x8e, 0xd0, 0x8e, 0xd8, 0xbd, 0x00, 0x7c, 0x8d,
0x66, 0xe0, 0xfb, 0xb8, 0xe0, 0x1f, 0x8e, 0xc0, 0x89, 0xee, 0x89, 0xef,
0xb9, 0x00, 0x01, 0xf3, 0xa5, 0xea, 0x22, 0x7c, 0xe0, 0x1f, 0x8e, 0xd8,
0x8e, 0xd0, 0x31, 0xc0, 0x8e, 0xc0, 0x8d, 0xbe, 0xbe, 0x01, 0xf6, 0x05,
0x80, 0x75, 0x6d, 0x83, 0xc7, 0x10, 0x81, 0xff, 0xfe, 0x7d, 0x72, 0xf2,
0xe8, 0xc4, 0x00, 0x6e, 0x6f, 0x20, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65,
0x20, 0x70, 0x61, 0x72, 0x74, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x66,
0x6f, 0x75, 0x6e, 0x64, 0x00, 0xeb, 0xfe, 0xe8, 0xa5, 0x00, 0x72, 0x65,
0x61, 0x64, 0x20, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x20, 0x77, 0x68, 0x69,
0x6c, 0x65, 0x20, 0x72, 0x65, 0x61, 0x64, 0x69, 0x6e, 0x67, 0x20, 0x64,
0x72, 0x69, 0x76, 0x65, 0x00, 0xeb, 0xda, 0xe8, 0x81, 0x00, 0x70, 0x61,
0x72, 0x74, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x73, 0x69, 0x67, 0x6e,
0x61, 0x74, 0x75, 0x72, 0x65, 0x20, 0x21, 0x3d, 0x20, 0x35, 0x35, 0x41,
0x41, 0x00, 0xeb, 0xb9, 0xe8, 0x10, 0x00, 0x72, 0xb6, 0x26, 0x81, 0x3e,
0xfe, 0x7d, 0x55, 0xaa, 0x75, 0xd1, 0xea, 0x00, 0x7c, 0x00, 0x00, 0xbb,
0xaa, 0x55, 0xb4, 0x41, 0xcd, 0x13, 0x72, 0x32, 0x81, 0xfb, 0x55, 0xaa,
0x75, 0x2c, 0xf6, 0xc1, 0x01, 0x74, 0x27, 0xeb, 0x10, 0x10, 0x00, 0x04,
0x00, 0x00, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x8b, 0x45, 0x08, 0xa3, 0xd1, 0x7c, 0x8b, 0x45, 0x0a, 0xa3, 0xd3,
0x7c, 0xb8, 0x00, 0x42, 0xbe, 0xc9, 0x7c, 0xcd, 0x13, 0xc3, 0xb8, 0x04,
0x02, 0xbb, 0x00, 0x7c, 0x8b, 0x4d, 0x02, 0x8a, 0x75, 0x01, 0xcd, 0x13,
0xc3, 0x31, 0xdb, 0xb4, 0x0e, 0xcd, 0x10, 0x5e, 0xac, 0x56, 0x3c, 0x00,
0x75, 0xf3, 0xc3
};
| 1,705 |
C
|
.c
| 26 | 63.692308 | 72 | 0.668255 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,818 |
bled.c
|
pbatard_rufus/src/bled/bled.c
|
/*
* Bled (Base Library for Easy Decompression)
*
* Copyright © 2014-2023 Pete Batard <[email protected]>
*
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
#ifdef _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#include "libbb.h"
#include "bb_archive.h"
#include "bled.h"
typedef long long int(*unpacker_t)(transformer_state_t *xstate);
/* Globals */
smallint bb_got_signal;
uint64_t bb_total_rb;
printf_t bled_printf = NULL;
read_t bled_read = NULL;
write_t bled_write = NULL;
progress_t bled_progress = NULL;
switch_t bled_switch = NULL;
unsigned long* bled_cancel_request;
static bool bled_initialized = 0;
jmp_buf bb_error_jmp;
char* bb_virtual_buf = NULL;
size_t bb_virtual_len = 0, bb_virtual_pos = 0;
int bb_virtual_fd = -1;
uint32_t BB_BUFSIZE = 0x10000;
static long long int unpack_none(transformer_state_t *xstate)
{
bb_error_msg("This compression type is not supported");
return -1;
}
unpacker_t unpacker[BLED_COMPRESSION_MAX] = {
unpack_none,
unpack_zip_stream,
unpack_Z_stream,
unpack_gz_stream,
unpack_lzma_stream,
unpack_bz2_stream,
unpack_xz_stream,
unpack_none,
unpack_vtsi_stream,
};
/* Uncompress file 'src', compressed using 'type', to file 'dst' */
int64_t bled_uncompress(const char* src, const char* dst, int type)
{
transformer_state_t xstate;
int64_t ret = -1;
if (!bled_initialized) {
bb_error_msg("The library has not been initialized");
return -1;
}
bb_total_rb = 0;
init_transformer_state(&xstate);
xstate.src_fd = -1;
xstate.dst_fd = -1;
xstate.src_fd = _openU(src, _O_RDONLY | _O_BINARY, 0);
if (xstate.src_fd < 0) {
bb_error_msg("Could not open '%s' (errno: %d)", src, errno);
goto err;
}
xstate.dst_fd = _openU(dst, _O_WRONLY | _O_CREAT | _O_TRUNC | _O_BINARY, _S_IREAD | _S_IWRITE);
if (xstate.dst_fd < 0) {
bb_error_msg("Could not open '%s' (errno: %d)", dst, errno);
goto err;
}
if ((type < 0) || (type >= BLED_COMPRESSION_MAX)) {
bb_error_msg("Unsupported compression format");
goto err;
}
if (setjmp(bb_error_jmp))
goto err;
ret = unpacker[type](&xstate);
err:
free(xstate.dst_name);
if (xstate.src_fd > 0)
_close(xstate.src_fd);
if (xstate.dst_fd > 0)
_close(xstate.dst_fd);
return ret;
}
/* Uncompress using Windows handles */
int64_t bled_uncompress_with_handles(HANDLE hSrc, HANDLE hDst, int type)
{
transformer_state_t xstate;
if (!bled_initialized) {
bb_error_msg("The library has not been initialized");
return -1;
}
bb_total_rb = 0;
init_transformer_state(&xstate);
xstate.src_fd = -1;
xstate.dst_fd = -1;
xstate.src_fd = _open_osfhandle((intptr_t)hSrc, _O_RDONLY);
if (xstate.src_fd < 0) {
bb_error_msg("Could not get source descriptor (errno: %d)", errno);
return -1;
}
xstate.dst_fd = _open_osfhandle((intptr_t)hDst, 0);
if (xstate.dst_fd < 0) {
bb_error_msg("Could not get target descriptor (errno: %d)", errno);
return -1;
}
if ((type < 0) || (type >= BLED_COMPRESSION_MAX)) {
bb_error_msg("Unsupported compression format");
return -1;
}
if (setjmp(bb_error_jmp))
return -1;
return unpacker[type](&xstate);
}
/* Uncompress file 'src', compressed using 'type', to buffer 'buf' of size 'size' */
int64_t bled_uncompress_to_buffer(const char* src, char* buf, size_t size, int type)
{
transformer_state_t xstate;
int64_t ret = -1;
if (!bled_initialized) {
bb_error_msg("The library has not been initialized");
return -1;
}
if ((src == NULL) || (buf == NULL)) {
bb_error_msg("Invalid parameter");
return -1;
}
bb_total_rb = 0;
init_transformer_state(&xstate);
xstate.src_fd = -1;
xstate.dst_fd = -1;
if (src[0] == 0) {
xstate.src_fd = bb_virtual_fd;
} else {
xstate.src_fd = _openU(src, _O_RDONLY | _O_BINARY, 0);
}
if (xstate.src_fd < 0) {
bb_error_msg("Could not open '%s' (errno: %d)", src, errno);
goto err;
}
xstate.mem_output_buf = buf;
xstate.mem_output_size = 0;
xstate.mem_output_size_max = size;
if ((type < 0) || (type >= BLED_COMPRESSION_MAX)) {
bb_error_msg("Unsupported compression format");
goto err;
}
if (setjmp(bb_error_jmp))
goto err;
ret = unpacker[type](&xstate);
err:
free(xstate.dst_name);
if ((src[0] != 0) && (xstate.src_fd > 0))
_close(xstate.src_fd);
return ret;
}
/* Uncompress all files from archive 'src', compressed using 'type', to destination dir 'dir' */
int64_t bled_uncompress_to_dir(const char* src, const char* dir, int type)
{
transformer_state_t xstate;
int64_t ret = -1;
if (!bled_initialized) {
bb_error_msg("The library has not been initialized");
return -1;
}
bb_total_rb = 0;
init_transformer_state(&xstate);
xstate.src_fd = -1;
xstate.dst_fd = -1;
xstate.src_fd = _openU(src, _O_RDONLY | _O_BINARY, 0);
if (xstate.src_fd < 0) {
bb_error_msg("Could not open '%s' (errno: %d)", src, errno);
goto err;
}
xstate.dst_dir = dir;
// Only zip archives are supported for now
if (type != BLED_COMPRESSION_ZIP) {
bb_error_msg("This compression format is not supported for directory extraction");
goto err;
}
if (setjmp(bb_error_jmp))
goto err;
ret = unpacker[type](&xstate);
err:
free(xstate.dst_name);
if (xstate.src_fd > 0)
_close(xstate.src_fd);
if (xstate.dst_fd > 0)
_close(xstate.dst_fd);
return ret;
}
int64_t bled_uncompress_from_buffer_to_buffer(const char* src, const size_t src_len, char* dst, size_t dst_len, int type)
{
int64_t ret;
if (!bled_initialized) {
bb_error_msg("The library has not been initialized");
return -1;
}
if ((src == NULL) || (dst == NULL)) {
bb_error_msg("Invalid parameter");
return -1;
}
if (bb_virtual_buf != NULL) {
bb_error_msg("Can not decompress more than one buffer at once");
return -1;
}
bb_virtual_buf = (char*)src;
bb_virtual_len = src_len;
bb_virtual_pos = 0;
bb_virtual_fd = 0;
ret = bled_uncompress_to_buffer("", dst, dst_len, type);
bb_virtual_buf = NULL;
bb_virtual_len = 0;
bb_virtual_fd = -1;
return ret;
}
/* Initialize the library.
* When the parameters are not NULL or zero you can:
* - specify the buffer size to use (must be larger than 64KB and a power of two)
* - specify the printf-like function you want to use to output message
* void print_function(const char* format, ...);
* - specify the read/write functions you want to use;
* - specify the function you want to use to display progress, based on number of source archive bytes read
* void progress_function(const uint64_t read_bytes);
* - specify the function you want to use when switching files in an archive
* void switch_function(const char* filename, const uint64_t filesize);
* - point to an unsigned long variable, to be used to cancel operations when set to non zero
*/
int bled_init(uint32_t buffer_size, printf_t print_function, read_t read_function, write_t write_function,
progress_t progress_function, switch_t switch_function, unsigned long* cancel_request)
{
if (bled_initialized)
return -1;
BB_BUFSIZE = buffer_size;
/* buffer_size must be larger than 64 KB and a power of two */
if (buffer_size < 0x10000 || (buffer_size & (buffer_size - 1)) != 0) {
if (buffer_size != 0 && print_function != NULL)
print_function("bled_init: invalid buffer_size, defaulting to 64 KB");
BB_BUFSIZE = 0x10000;
}
bled_printf = print_function;
bled_read = read_function;
bled_write = write_function;
bled_progress = progress_function;
bled_switch = switch_function;
bled_cancel_request = cancel_request;
bled_initialized = true;
return 0;
}
/* This call frees any resource used by the library */
void bled_exit(void)
{
bled_printf = NULL;
bled_progress = NULL;
bled_switch = NULL;
bled_cancel_request = NULL;
if (global_crc32_table) {
free(global_crc32_table);
global_crc32_table = NULL;
}
bled_initialized = false;
}
| 7,767 |
C
|
.c
| 262 | 27.465649 | 121 | 0.696096 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
4,845 |
grub2_version.h
|
pbatard_rufus/res/grub2/grub2_version.h
|
/*
* This file contains the version string of the GRUB 2.x binary embedded in Rufus.
* Should be the same as GRUB's PACKAGE_VERSION in config.h.
*/
#pragma once
#define GRUB2_PACKAGE_VERSION "2.12"
| 202 |
C
|
.h
| 6 | 32 | 82 | 0.753846 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
4,851 |
grub_version.h
|
pbatard_rufus/res/grub/grub_version.h
|
/*
* This file contains the version string of the Grub4Dos 2.x binary embedded in Rufus.
* Should be the same as the grub4dos_version file in the source Grub4Dos was compiled from.
*/
#define GRUB4DOS_VERSION "0.4.6a"
| 221 |
C
|
.h
| 5 | 42.6 | 92 | 0.768519 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,854 |
gpt_types.h
|
pbatard_rufus/src/gpt_types.h
|
/*
* Rufus: The Reliable USB Formatting Utility
* GPT Partition Types
* Copyright © 2020 Pete Batard <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <windows.h>
// MinGW won't properly embed the GUIDs unless the following is defined
#define INITGUID
#include <guiddef.h>
#pragma once
/*
* From https://en.wikipedia.org/wiki/GUID_Partition_Table
*/
DEFINE_GUID(PARTITION_ANDROID_BOOT, 0x49A4D17F, 0x93A3, 0x45C1, 0xA0, 0xDE, 0xF5, 0x0B, 0x2E, 0xBE, 0x25, 0x99);
DEFINE_GUID(PARTITION_ANDROID_BOOTLOADER1, 0x2568845D, 0x2332, 0x4675, 0xBC, 0x39, 0x8F, 0xA5, 0xA4, 0x74, 0x8D, 0x15);
DEFINE_GUID(PARTITION_ANDROID_BOOTLOADER2, 0x114EAFFE, 0x1552, 0x4022, 0xB2, 0x6E, 0x9B, 0x05, 0x36, 0x04, 0xCF, 0x84);
DEFINE_GUID(PARTITION_ANDROID_CACHE, 0xA893EF21, 0xE428, 0x470A, 0x9E, 0x55, 0x06, 0x68, 0xFD, 0x91, 0xA2, 0xD9);
DEFINE_GUID(PARTITION_ANDROID_CONFIG, 0xBD59408B, 0x4514, 0x490D, 0xBF, 0x12, 0x98, 0x78, 0xD9, 0x63, 0xF3, 0x78);
DEFINE_GUID(PARTITION_ANDROID_DATA, 0xDC76DDA9, 0x5AC1, 0x491C, 0xAF, 0x42, 0xA8, 0x25, 0x91, 0x58, 0x0C, 0x0D);
DEFINE_GUID(PARTITION_ANDROID_EXT, 0x193D1EA4, 0xB3CA, 0x11E4, 0xB0, 0x75, 0x10, 0x60, 0x4B, 0x88, 0x9D, 0xCF);
DEFINE_GUID(PARTITION_ANDROID_FACTORY1, 0x8F68CC74, 0xC5E5, 0x48DA, 0xBE, 0x91, 0xA0, 0xC8, 0xC1, 0x5E, 0x9C, 0x80);
DEFINE_GUID(PARTITION_ANDROID_FACTORY2, 0x9FDAA6EF, 0x4B3F, 0x40D2, 0xBA, 0x8D, 0xBF, 0xF1, 0x6B, 0xFB, 0x88, 0x7B);
DEFINE_GUID(PARTITION_ANDROID_FASTBOOT, 0x767941D0, 0x2085, 0x11E3, 0xAD, 0x3B, 0x6C, 0xFD, 0xB9, 0x47, 0x11, 0xE9);
DEFINE_GUID(PARTITION_ANDROID_METADATA1, 0x20AC26BE, 0x20B7, 0x11E3, 0x84, 0xC5, 0x6C, 0xFD, 0xB9, 0x47, 0x11, 0xE9);
DEFINE_GUID(PARTITION_ANDROID_METADATA2, 0x19A710A2, 0xB3CA, 0x11E4, 0xB0, 0x26, 0x10, 0x60, 0x4B, 0x88, 0x9D, 0xCF);
DEFINE_GUID(PARTITION_ANDROID_MISC, 0xEF32A33B, 0xA409, 0x486C, 0x91, 0x41, 0x9F, 0xFB, 0x71, 0x1F, 0x62, 0x66);
DEFINE_GUID(PARTITION_ANDROID_OEM, 0xAC6D7924, 0xEB71, 0x4DF8, 0xB4, 0x8D, 0xE2, 0x67, 0xB2, 0x71, 0x48, 0xFF);
DEFINE_GUID(PARTITION_ANDROID_PERSISTENCE, 0xEBC597D0, 0x2053, 0x4B15, 0x8B, 0x64, 0xE0, 0xAA, 0xC7, 0x5F, 0x4D, 0xB1);
DEFINE_GUID(PARTITION_ANDROID_RECOVERY, 0x4177C722, 0x9E92, 0x4AAB, 0x86, 0x44, 0x43, 0x50, 0x2B, 0xFD, 0x55, 0x06);
DEFINE_GUID(PARTITION_ANDROID_SYSTEM, 0x38F428E6, 0xD326, 0x425D, 0x91, 0x40, 0x6E, 0x0E, 0xA1, 0x33, 0x64, 0x7C);
DEFINE_GUID(PARTITION_ANDROID_VENDOR, 0xC5A0AEEC, 0x13EA, 0x11E5, 0xA1, 0xB1, 0x00, 0x1E, 0x67, 0xCA, 0x0C, 0x3C);
DEFINE_GUID(PARTITION_APPLE_APFS, 0x7C3457EF, 0x0000, 0x11AA, 0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC);
DEFINE_GUID(PARTITION_APPLE_BOOT, 0x426F6F74, 0x0000, 0x11AA, 0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC);
DEFINE_GUID(PARTITION_APPLE_FILEVAULT, 0x53746F72, 0x6167, 0x11AA, 0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC);
DEFINE_GUID(PARTITION_APPLE_HFS, 0x48465300, 0x0000, 0x11AA, 0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC);
DEFINE_GUID(PARTITION_APPLE_LABEL, 0x4C616265, 0x6C00, 0x11AA, 0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC);
DEFINE_GUID(PARTITION_APPLE_OFFLINE_RAID, 0x52414944, 0x5F4F, 0x11AA, 0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC);
DEFINE_GUID(PARTITION_APPLE_RAID, 0x52414944, 0x0000, 0x11AA, 0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC);
DEFINE_GUID(PARTITION_APPLE_RAID_CACHE, 0xBBBA6DF5, 0xF46F, 0x4A89, 0x8F, 0x59, 0x87, 0x65, 0xB2, 0x72, 0x75, 0x03);
DEFINE_GUID(PARTITION_APPLE_RAID_SCRATCH, 0x2E313465, 0x19B9, 0x463F, 0x81, 0x26, 0x8A, 0x79, 0x93, 0x77, 0x38, 0x01);
DEFINE_GUID(PARTITION_APPLE_RAID_STATUS, 0xB6FA30DA, 0x92D2, 0x4A9A, 0x96, 0xF1, 0x87, 0x1E, 0xC6, 0x48, 0x62, 0x00);
DEFINE_GUID(PARTITION_APPLE_RAID_VOLUME, 0xFA709C7E, 0x65B1, 0x4593, 0xBF, 0xD5, 0xE7, 0x1D, 0x61, 0xDE, 0x9B, 0x02);
DEFINE_GUID(PARTITION_APPLE_RECOVERY, 0x5265636F, 0x7665, 0x11AA, 0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC);
DEFINE_GUID(PARTITION_APPLE_UFS, 0x55465300, 0x0000, 0x11AA, 0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC);
// Stolen from Solaris below. Great job here, Apple! Then again, Oracle can and *should* go to hell, so who cares...
DEFINE_GUID(PARTITION_APPLE_ZFS, 0x6A898CC3, 0x1DD2, 0x11B2, 0x99, 0xA6, 0x08, 0x00, 0x20, 0x73, 0x66, 0x31);
DEFINE_GUID(PARTITION_ATARI_DATA, 0x734E5AFE, 0xF61A, 0x11E6, 0xBC, 0x64, 0x92, 0x36, 0x1F, 0x00, 0x26, 0x71);
DEFINE_GUID(PARTITION_BEOS_BFS, 0x42465331, 0x3BA3, 0x10F1, 0x80, 0x2A, 0x48, 0x61, 0x69, 0x6B, 0x75, 0x21);
DEFINE_GUID(PARTITION_CHROMEOS_KERNEL, 0xFE3A2A5D, 0x4F32, 0x41A7, 0xB7, 0x25, 0xAC, 0xCC, 0x32, 0x85, 0xA3, 0x09);
DEFINE_GUID(PARTITION_CHROMEOS_RESERVED, 0x2E0A753D, 0x9E48, 0x43B0, 0x83, 0x37, 0xB1, 0x51, 0x92, 0xCB, 0x1B, 0x5E);
DEFINE_GUID(PARTITION_CHROMEOS_ROOT, 0x3CB8E202, 0x3B7E, 0x47DD, 0x8A, 0x3C, 0x7F, 0xF2, 0xA1, 0x3C, 0xFC, 0xEC);
DEFINE_GUID(PARTITION_COREOS_RAID, 0xBE9067B9, 0xEA49, 0x4F15, 0xB4, 0xF6, 0xF3, 0x6F, 0x8C, 0x9E, 0x18, 0x18);
DEFINE_GUID(PARTITION_COREOS_RESERVED, 0xC95DC21A, 0xDF0E, 0x4340, 0x8D, 0x7B, 0x26, 0xCB, 0xFA, 0x9A, 0x03, 0xE0);
DEFINE_GUID(PARTITION_COREOS_ROOT, 0x3884DD41, 0x8582, 0x4404, 0xB9, 0xA8, 0xE9, 0xB8, 0x4F, 0x2D, 0xF5, 0x0E);
DEFINE_GUID(PARTITION_COREOS_USR, 0x5DFBF5F4, 0x2848, 0x4BAC, 0xAA, 0x5E, 0x0D, 0x9A, 0x20, 0xB7, 0x45, 0xA6);
DEFINE_GUID(PARTITION_FREEBSD_BOOT, 0x83BD6B9D, 0x7F41, 0x11DC, 0xBE, 0x0B, 0x00, 0x15, 0x60, 0xB8, 0x4F, 0x0F);
DEFINE_GUID(PARTITION_FREEBSD_DATA, 0x516E7CB4, 0x6ECF, 0x11D6, 0x8F, 0xF8, 0x00, 0x02, 0x2D, 0x09, 0x71, 0x2B);
DEFINE_GUID(PARTITION_FREEBSD_LVM, 0x516E7CB8, 0x6ECF, 0x11D6, 0x8F, 0xF8, 0x00, 0x02, 0x2D, 0x09, 0x71, 0x2B);
DEFINE_GUID(PARTITION_FREEBSD_SWAP, 0x516E7CB5, 0x6ECF, 0x11D6, 0x8F, 0xF8, 0x00, 0x02, 0x2D, 0x09, 0x71, 0x2B);
DEFINE_GUID(PARTITION_FREEBSD_UFS, 0x516E7CB6, 0x6ECF, 0x11D6, 0x8F, 0xF8, 0x00, 0x02, 0x2D, 0x09, 0x71, 0x2B);
DEFINE_GUID(PARTITION_FREEBSD_ZFS, 0x516E7CBA, 0x6ECF, 0x11D6, 0x8F, 0xF8, 0x00, 0x02, 0x2D, 0x09, 0x71, 0x2B);
DEFINE_GUID(PARTITION_GENERIC_BIOS_BOOT, 0x21686148, 0x6449, 0x6E6F, 0x74, 0x4E, 0x65, 0x65, 0x64, 0x45, 0x46, 0x49);
DEFINE_GUID(PARTITION_GENERIC_XBOOTLDR, 0xBC13C2FF, 0x59E6, 0x4262, 0xA3, 0x52, 0xB2, 0x75, 0xFD, 0x6F, 0x71, 0x72);
DEFINE_GUID(PARTITION_GENERIC_ESP, 0xC12A7328, 0xF81F, 0x11D2, 0xBA, 0x4B, 0x00, 0xA0, 0xC9, 0x3E, 0xC9, 0x3B);
DEFINE_GUID(PARTITION_GENERIC_MBR, 0x024DEE41, 0x33E7, 0x11D3, 0x9D, 0x69, 0x00, 0x08, 0xC7, 0x81, 0xF3, 0x9F);
DEFINE_GUID(PARTITION_GENERIC_UNUSED, 0x00000000, 0x0000, 0x0000, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00);
DEFINE_GUID(PARTITION_HPUX_DATA, 0x75894C1E, 0x3AEB, 0x11D3, 0xB7, 0xC1, 0x7B, 0x03, 0xA0, 0x00, 0x00, 0x00);
DEFINE_GUID(PARTITION_HPUX_SERVICE, 0xE2A1E728, 0x32E3, 0x11D6, 0xA6, 0x82, 0x7B, 0x03, 0xA0, 0x00, 0x00, 0x00);
DEFINE_GUID(PARTITION_IBM_GPFS, 0x37AFFC90, 0xEF7D, 0x4E96, 0x91, 0xC3, 0x2D, 0x7A, 0xE0, 0x55, 0xB1, 0x74);
DEFINE_GUID(PARTITION_INTEL_IFF, 0xD3BFE2DE, 0x3DAF, 0x11DF, 0xBA, 0x40, 0xE3, 0xA5, 0x56, 0xD8, 0x95, 0x93);
DEFINE_GUID(PARTITION_LENOVO_BOOT, 0xBFBFAFE7, 0xA34F, 0x448A, 0x9A, 0x5B, 0x62, 0x13, 0xEB, 0x73, 0x6C, 0x22);
DEFINE_GUID(PARTITION_LINUX_BOOT, 0xBC13C2FF, 0x59E6, 0x4262, 0xA3, 0x52, 0xB2, 0x75, 0xFD, 0x6F, 0x71, 0x72);
DEFINE_GUID(PARTITION_LINUX_DATA, 0x0FC63DAF, 0x8483, 0x4772, 0x8E, 0x79, 0x3D, 0x69, 0xD8, 0x47, 0x7D, 0xE4);
DEFINE_GUID(PARTITION_LINUX_ENCRYPTED, 0x7FFEC5C9, 0x2D00, 0x49B7, 0x89, 0x41, 0x3E, 0xA1, 0x0A, 0x55, 0x86, 0xB7);
DEFINE_GUID(PARTITION_LINUX_HOME, 0x933AC7E1, 0x2EB4, 0x4F13, 0xB8, 0x44, 0x0E, 0x14, 0xE2, 0xAE, 0xF9, 0x15);
DEFINE_GUID(PARTITION_LINUX_LUKS, 0xCA7D7CCB, 0x63ED, 0x4C53, 0x86, 0x1C, 0x17, 0x42, 0x53, 0x60, 0x59, 0xCC);
DEFINE_GUID(PARTITION_LINUX_LVM, 0xE6D6D379, 0xF507, 0x44C2, 0xA2, 0x3C, 0x23, 0x8F, 0x2A, 0x3D, 0xF9, 0x28);
DEFINE_GUID(PARTITION_LINUX_RAID, 0xA19D880F, 0x05FC, 0x4D3B, 0xA0, 0x06, 0x74, 0x3F, 0x0F, 0x84, 0x91, 0x1E);
DEFINE_GUID(PARTITION_LINUX_RESERVED, 0x8DA63339, 0x0007, 0x60C0, 0xC4, 0x36, 0x08, 0x3A, 0xC8, 0x23, 0x09, 0x08);
DEFINE_GUID(PARTITION_LINUX_ROOT_ARM_32, 0x69DAD710, 0x2CE4, 0x4E3C, 0xB1, 0x6C, 0x21, 0xA1, 0xD4, 0x9A, 0xBE, 0xD3);
DEFINE_GUID(PARTITION_LINUX_ROOT_ARM_64, 0xB921B045, 0x1DF0, 0x41C3, 0xAF, 0x44, 0x4C, 0x6F, 0x28, 0x0D, 0x3F, 0xAE);
DEFINE_GUID(PARTITION_LINUX_ROOT_X86_32, 0x44479540, 0xF297, 0x41B2, 0x9A, 0xF7, 0xD1, 0x31, 0xD5, 0xF0, 0x45, 0x8A);
DEFINE_GUID(PARTITION_LINUX_ROOT_X86_64, 0x4F68BCE3, 0xE8CD, 0x4DB1, 0x96, 0xE7, 0xFB, 0xCA, 0xF9, 0x84, 0xB7, 0x09);
DEFINE_GUID(PARTITION_LINUX_SRV, 0x3B8F8425, 0x20E0, 0x4F3B, 0x90, 0x7F, 0x1A, 0x25, 0xA7, 0x6F, 0x98, 0xE8);
DEFINE_GUID(PARTITION_LINUX_SWAP, 0x0657FD6D, 0xA4AB, 0x43C4, 0x84, 0xE5, 0x09, 0x33, 0xC8, 0x4B, 0x4F, 0x4F);
DEFINE_GUID(PARTITION_MICROSOFT_DATA, 0xEBD0A0A2, 0xB9E5, 0x4433, 0x87, 0xC0, 0x68, 0xB6, 0xB7, 0x26, 0x99, 0xC7);
DEFINE_GUID(PARTITION_MICROSOFT_LDM_DATA, 0xAF9B60A0, 0x1431, 0x4F62, 0xBC, 0x68, 0x33, 0x11, 0x71, 0x4A, 0x69, 0xAD);
DEFINE_GUID(PARTITION_MICROSOFT_LDM_META, 0x5808C8AA, 0x7E8F, 0x42E0, 0x85, 0xD2, 0xE1, 0xE9, 0x04, 0x34, 0xCF, 0xB3);
DEFINE_GUID(PARTITION_MICROSOFT_RECOVERY, 0xDE94BBA4, 0x06D1, 0x4D40, 0xA1, 0x6A, 0xBF, 0xD5, 0x01, 0x79, 0xD6, 0xAC);
DEFINE_GUID(PARTITION_MICROSOFT_RESERVED, 0xE3C9E316, 0x0B5C, 0x4DB8, 0x81, 0x7D, 0xF9, 0x2D, 0xF0, 0x02, 0x15, 0xAE);
DEFINE_GUID(PARTITION_MICROSOFT_STORAGE_SPACES, 0xE75CAF8F, 0xF680, 0x4CEE, 0xAF, 0xA3, 0xB0, 0x01, 0xE5, 0x6E, 0xFC, 0x2D);
DEFINE_GUID(PARTITION_NETBSD_CONCAT, 0x2DB519C4, 0xB10F, 0x11DC, 0xB9, 0x9B, 0x00, 0x19, 0xD1, 0x87, 0x96, 0x48);
DEFINE_GUID(PARTITION_NETBSD_ENCRYPTED, 0x2DB519EC, 0xB10F, 0x11DC, 0xB9, 0x9B, 0x00, 0x19, 0xD1, 0x87, 0x96, 0x48);
DEFINE_GUID(PARTITION_NETBSD_FFS, 0x49F48D5A, 0xB10E, 0x11DC, 0xB9, 0x9B, 0x00, 0x19, 0xD1, 0x87, 0x96, 0x48);
DEFINE_GUID(PARTITION_NETBSD_LFS, 0x49F48D82, 0xB10E, 0x11DC, 0xB9, 0x9B, 0x00, 0x19, 0xD1, 0x87, 0x96, 0x48);
DEFINE_GUID(PARTITION_NETBSD_RAID, 0x49F48DAA, 0xB10E, 0x11DC, 0xB9, 0x9B, 0x00, 0x19, 0xD1, 0x87, 0x96, 0x48);
DEFINE_GUID(PARTITION_NETBSD_SWAP, 0x49F48D32, 0xB10E, 0x11DC, 0xB9, 0x9B, 0x00, 0x19, 0xD1, 0x87, 0x96, 0x48);
DEFINE_GUID(PARTITION_OPENBSD_DATA, 0x824CC7A0, 0x36A8, 0x11E3, 0x89, 0x0A, 0x95, 0x25, 0x19, 0xAD, 0x3F, 0x61);
DEFINE_GUID(PARTITION_PLAN9_DATA, 0xC91818F9, 0x8025, 0x47AF, 0x89, 0xD2, 0xF0, 0x30, 0xD7, 0x00, 0x0C, 0x2C);
DEFINE_GUID(PARTITION_PREP_BOOT, 0x9E1A2D38, 0xC612, 0x4316, 0xAA, 0x26, 0x8B, 0x49, 0x52, 0x1E, 0x5A, 0x8B);
DEFINE_GUID(PARTITION_QNX_DATA, 0xCEF5A9AD, 0x73BC, 0x4601, 0x89, 0xF3, 0xCD, 0xEE, 0xEE, 0xE3, 0x21, 0xA1);
DEFINE_GUID(PARTITION_SOLARIS_ALT, 0x6A9283A5, 0x1DD2, 0x11B2, 0x99, 0xA6, 0x08, 0x00, 0x20, 0x73, 0x66, 0x31);
DEFINE_GUID(PARTITION_SOLARIS_BACKUP, 0x6A8B642B, 0x1DD2, 0x11B2, 0x99, 0xA6, 0x08, 0x00, 0x20, 0x73, 0x66, 0x31);
DEFINE_GUID(PARTITION_SOLARIS_BOOT, 0x6A82CB45, 0x1DD2, 0x11B2, 0x99, 0xA6, 0x08, 0x00, 0x20, 0x73, 0x66, 0x31);
DEFINE_GUID(PARTITION_SOLARIS_HOME, 0x6A90BA39, 0x1DD2, 0x11B2, 0x99, 0xA6, 0x08, 0x00, 0x20, 0x73, 0x66, 0x31);
DEFINE_GUID(PARTITION_SOLARIS_RESERVED1, 0x6A945A3B, 0x1DD2, 0x11B2, 0x99, 0xA6, 0x08, 0x00, 0x20, 0x73, 0x66, 0x31);
DEFINE_GUID(PARTITION_SOLARIS_RESERVED2, 0x6A9630D1, 0x1DD2, 0x11B2, 0x99, 0xA6, 0x08, 0x00, 0x20, 0x73, 0x66, 0x31);
DEFINE_GUID(PARTITION_SOLARIS_RESERVED3, 0x6A980767, 0x1DD2, 0x11B2, 0x99, 0xA6, 0x08, 0x00, 0x20, 0x73, 0x66, 0x31);
DEFINE_GUID(PARTITION_SOLARIS_RESERVED4, 0x6A96237F, 0x1DD2, 0x11B2, 0x99, 0xA6, 0x08, 0x00, 0x20, 0x73, 0x66, 0x31);
DEFINE_GUID(PARTITION_SOLARIS_RESERVED5, 0x6A8D2AC7, 0x1DD2, 0x11B2, 0x99, 0xA6, 0x08, 0x00, 0x20, 0x73, 0x66, 0x31);
// You sure you don't need a couple more reserved partition GUIDs here, Solaris?
DEFINE_GUID(PARTITION_SOLARIS_ROOT, 0x6A85CF4D, 0x1DD2, 0x11B2, 0x99, 0xA6, 0x08, 0x00, 0x20, 0x73, 0x66, 0x31);
DEFINE_GUID(PARTITION_SOLARIS_SWAP, 0x6A87C46F, 0x1DD2, 0x11B2, 0x99, 0xA6, 0x08, 0x00, 0x20, 0x73, 0x66, 0x31);
//DEFINE_GUID(PARTITION_SOLARIS_USR, 0x6A898CC3, 0x1DD2, 0x11B2, 0x99, 0xA6, 0x08, 0x00, 0x20, 0x73, 0x66, 0x31);
DEFINE_GUID(PARTITION_SOLARIS_VAR, 0x6A8EF2E9, 0x1DD2, 0x11B2, 0x99, 0xA6, 0x08, 0x00, 0x20, 0x73, 0x66, 0x31);
DEFINE_GUID(PARTITION_SONY_BOOT, 0xF4019732, 0x066E, 0x4E12, 0x82, 0x73, 0x34, 0x6C, 0x56, 0x41, 0x49, 0x4F);
DEFINE_GUID(PARTITION_VERACRYPT_DATA, 0x8C8F8EFF, 0xAC95, 0x4770, 0x81, 0x4A, 0x21, 0x99, 0x4F, 0x2D, 0xBC, 0x8F);
DEFINE_GUID(PARTITION_VMWARE_COREDUMP, 0x9D275380, 0x40AD, 0x11DB, 0xBF, 0x97, 0x00, 0x0C, 0x29, 0x11, 0xD1, 0xB8);
DEFINE_GUID(PARTITION_VMWARE_RESERVED, 0x9198EFFC, 0x31C0, 0x11DB, 0x8F, 0x78, 0x00, 0x0C, 0x29, 0x11, 0xD1, 0xB8);
DEFINE_GUID(PARTITION_VMWARE_VMFS, 0xAA31E02A, 0x400F, 0x11DB, 0x95, 0x90, 0x00, 0x0C, 0x29, 0x11, 0xD1, 0xB8);
typedef struct {
const GUID* guid;
const char* name;
} gpt_type_t;
gpt_type_t gpt_type[] = {
{ &PARTITION_ANDROID_BOOT, "Android Boot Partition" },
{ &PARTITION_ANDROID_BOOTLOADER1, "Android Bootloader Partition" },
{ &PARTITION_ANDROID_BOOTLOADER2, "Android Bootloader Partition" },
{ &PARTITION_ANDROID_CACHE, "Android Cache Partition" },
{ &PARTITION_ANDROID_CONFIG, "Android Config Partition" },
{ &PARTITION_ANDROID_DATA, "Android Data Partition" },
{ &PARTITION_ANDROID_EXT, "Android Ext Partition" },
{ &PARTITION_ANDROID_FACTORY1, "Android Factory Partition" },
{ &PARTITION_ANDROID_FACTORY2, "Android Factory Partition" },
{ &PARTITION_ANDROID_FASTBOOT, "Android Fastboot Partition" },
{ &PARTITION_ANDROID_METADATA1, "Android Metadata Partition" },
{ &PARTITION_ANDROID_METADATA2, "Android Metadata Partition" },
{ &PARTITION_ANDROID_MISC, "Android Misc Partition" },
{ &PARTITION_ANDROID_OEM, "Android OEM Partition" },
{ &PARTITION_ANDROID_PERSISTENCE, "Android Persistent Partition" },
{ &PARTITION_ANDROID_RECOVERY, "Android Recovery Partition" },
{ &PARTITION_ANDROID_SYSTEM, "Android System Partition" },
{ &PARTITION_ANDROID_VENDOR, "Android Vendor Partition" },
{ &PARTITION_APPLE_APFS, "Apple APFS Partition" },
{ &PARTITION_APPLE_BOOT, "Apple Boot Partition" },
{ &PARTITION_APPLE_FILEVAULT, "Apple Filevault Partition" },
{ &PARTITION_APPLE_HFS, "Apple HFS+ Partition" },
{ &PARTITION_APPLE_LABEL, "Apple Label Partition" },
{ &PARTITION_APPLE_OFFLINE_RAID, "Apple RAID Partition (Offline)" },
{ &PARTITION_APPLE_RAID, "Apple RAID Partition" },
{ &PARTITION_APPLE_RAID_CACHE, "Apple RAID Cache Partition" },
{ &PARTITION_APPLE_RAID_SCRATCH, "Apple RAID Scratch Partition" },
{ &PARTITION_APPLE_RAID_STATUS, "Apple RAID Status Partition" },
{ &PARTITION_APPLE_RAID_VOLUME, "Apple RAID Volume Partition" },
{ &PARTITION_APPLE_RECOVERY, "Apple Recovery Partition" },
{ &PARTITION_APPLE_UFS, "Apple UFS Partition" },
{ &PARTITION_APPLE_ZFS, "Apple ZFS Partition" },
{ &PARTITION_ATARI_DATA, "Atari Data Partition" },
{ &PARTITION_BEOS_BFS, "BeOS BFS Partition" },
{ &PARTITION_CHROMEOS_KERNEL, "Chrome OS Kernel Partition" },
{ &PARTITION_CHROMEOS_RESERVED, "Chrome OS Reserved Partition" },
{ &PARTITION_CHROMEOS_ROOT, "Chrome OS Root Partition" },
{ &PARTITION_COREOS_RAID, "CoreOS Raid Partition" },
{ &PARTITION_COREOS_RESERVED, "CoreOS Reserved Partition" },
{ &PARTITION_COREOS_ROOT, "CoreOS Root Partition" },
{ &PARTITION_COREOS_USR, "CoreOS Usr Partition" },
{ &PARTITION_FREEBSD_BOOT, "FreeBSD Boot Partition" },
{ &PARTITION_FREEBSD_DATA, "FreeBSD Data Partition" },
{ &PARTITION_FREEBSD_LVM, "FreeBSD LVM Partition" },
{ &PARTITION_FREEBSD_SWAP, "FreeBSD Swap Partition" },
{ &PARTITION_FREEBSD_UFS, "FreeBSD UFS Partition" },
{ &PARTITION_FREEBSD_ZFS, "FreeBSD ZFS Partition" },
{ &PARTITION_GENERIC_BIOS_BOOT, "BIOS Boot Partition" },
{ &PARTITION_GENERIC_XBOOTLDR, "Extended Boot Loader Partition" },
{ &PARTITION_GENERIC_ESP, "EFI System Partition" },
{ &PARTITION_GENERIC_MBR, "MBR Partition" },
{ &PARTITION_GENERIC_UNUSED, "Unused Partition" },
{ &PARTITION_HPUX_DATA, "HP-UX Data Partition" },
{ &PARTITION_HPUX_SERVICE, "HP-UX Service Partition" },
{ &PARTITION_IBM_GPFS, "IBM GPFS Partition" },
{ &PARTITION_INTEL_IFF, "Intel Fast Flash Partition" },
{ &PARTITION_LENOVO_BOOT, "Lenovo Boot Partition" },
{ &PARTITION_LINUX_BOOT, "Linux Boot Partition" },
{ &PARTITION_LINUX_DATA, "Linux Data Partition" },
{ &PARTITION_LINUX_ENCRYPTED, "Linux Encrypted Partition" },
{ &PARTITION_LINUX_HOME, "Linux Home Partition" },
{ &PARTITION_LINUX_LUKS, "Linux LUKS Partition" },
{ &PARTITION_LINUX_LVM, "Linux LVM Partition" },
{ &PARTITION_LINUX_RAID, "Linux RAID Partition" },
{ &PARTITION_LINUX_RESERVED, "Linux Reserved Partition" },
{ &PARTITION_LINUX_ROOT_ARM_32, "Linux Boot Partition (ARM)" },
{ &PARTITION_LINUX_ROOT_ARM_64, "Linux Boot Partition (ARM64)" },
{ &PARTITION_LINUX_ROOT_X86_32, "Linux Boot Partition (x86-32)" },
{ &PARTITION_LINUX_ROOT_X86_64, "Linux Boot Partition (x86-64)" },
{ &PARTITION_LINUX_SRV, "Linux Srv Partition" },
{ &PARTITION_LINUX_SWAP, "Linux Swap Partition" },
{ &PARTITION_MICROSOFT_DATA, "Microsoft Basic Data Partition" },
{ &PARTITION_MICROSOFT_LDM_DATA, "Microsoft LDM Data Partition" },
{ &PARTITION_MICROSOFT_LDM_META, "Microsoft LDM Metadata Partition" },
{ &PARTITION_MICROSOFT_RECOVERY, "Microsoft Recovery Partition" },
{ &PARTITION_MICROSOFT_RESERVED, "Microsoft System Reserved Partition" },
{ &PARTITION_MICROSOFT_STORAGE_SPACES, "Microsoft Storage Spaces Partition" },
{ &PARTITION_NETBSD_CONCAT, "NetBSD Concatenated Partition" },
{ &PARTITION_NETBSD_ENCRYPTED, "NetBSD Encrypted Partition" },
{ &PARTITION_NETBSD_FFS, "NetBSD FFS Partition" },
{ &PARTITION_NETBSD_LFS, "NetBSD LFS Partition" },
{ &PARTITION_NETBSD_RAID, "NetBSD RAID Partition" },
{ &PARTITION_NETBSD_SWAP, "NetBSD Swap Partition" },
{ &PARTITION_OPENBSD_DATA, "OpenBSD Data Partition" },
{ &PARTITION_PLAN9_DATA, "Plan 9 Data Partition" },
{ &PARTITION_PREP_BOOT, "PReP Boot Partition" },
{ &PARTITION_QNX_DATA, "QNX Data Partition" },
{ &PARTITION_SOLARIS_ALT, "Solaris Alternate Sector Partition" },
{ &PARTITION_SOLARIS_BACKUP, "Solaris Backup Partition" },
{ &PARTITION_SOLARIS_BOOT, "Solaris Boot Partition" },
{ &PARTITION_SOLARIS_HOME, "Solaris Home Partition" },
{ &PARTITION_SOLARIS_RESERVED1, "Solaris Reserved Partition" },
{ &PARTITION_SOLARIS_RESERVED2, "Solaris Reserved Partition" },
{ &PARTITION_SOLARIS_RESERVED3, "Solaris Reserved Partition" },
{ &PARTITION_SOLARIS_RESERVED4, "Solaris Reserved Partition" },
{ &PARTITION_SOLARIS_RESERVED5, "Solaris Reserved Partition" },
{ &PARTITION_SOLARIS_ROOT, "Solaris Root Partition" },
{ &PARTITION_SOLARIS_SWAP, "Solaris Swap Partition" },
// { &PARTITION_SOLARIS_USR, "Solaris Usr Partition" },
{ &PARTITION_SOLARIS_VAR, "Solaris Var Partition" },
{ &PARTITION_SONY_BOOT, "Sony Boot Partition" },
{ &PARTITION_VERACRYPT_DATA, "VeraCrypt Data Partition" },
{ &PARTITION_VMWARE_COREDUMP, "VMware Coredump Partition" },
{ &PARTITION_VMWARE_RESERVED, "VMware Reserved Partition" },
{ &PARTITION_VMWARE_VMFS, "VMware VMFS Partition" },
};
| 19,758 |
C
|
.h
| 244 | 78.139344 | 124 | 0.732636 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,858 |
ui.h
|
pbatard_rufus/src/ui.h
|
/*
* Rufus: The Reliable USB Formatting Utility
* UI-related function calls
* Copyright © 2018 Pete Batard <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <windows.h>
#include <stdint.h>
#include "resource.h"
#include "localization.h"
#pragma once
// Progress bar colors
#define PROGRESS_BAR_NORMAL_TEXT_COLOR RGB(0x00, 0x00, 0x00)
#define PROGRESS_BAR_INVERTED_TEXT_COLOR RGB(0xFF, 0xFF, 0xFF)
#define PROGRESS_BAR_BACKGROUND_COLOR RGB(0xE6, 0xE6, 0xE6)
#define PROGRESS_BAR_BOX_COLOR RGB(0xBC, 0xBC, 0xBC)
#define PROGRESS_BAR_NORMAL_COLOR RGB(0x06, 0xB0, 0x25)
#define PROGRESS_BAR_PAUSED_COLOR RGB(0xDA, 0xCB, 0x26)
#define PROGRESS_BAR_ERROR_COLOR RGB(0xDA, 0x26, 0x26)
// Toolbar icons main color
#define TOOLBAR_ICON_COLOR RGB(0x29, 0x80, 0xB9)
// Toolbar default style
#define TOOLBAR_STYLE ( WS_CHILD | WS_TABSTOP | WS_VISIBLE | \
WS_CLIPSIBLINGS | WS_CLIPCHILDREN | \
CCS_NOPARENTALIGN | CCS_NODIVIDER | \
TBSTYLE_FLAT | TBSTYLE_BUTTON | \
TBSTYLE_AUTOSIZE | TBSTYLE_LIST | \
TBSTYLE_TOOLTIPS )
// Types of update progress we report
enum update_progress_type {
UPT_PERCENT = 0,
UPT_SPEED,
UPT_ETA,
UPT_MAX
};
// Size of the download speed history ring.
#define SPEED_HISTORY_SIZE 20
// The minimum time length of a history sample. By default, each sample is at least 150ms long,
// which means that, over the course of 20 samples, "current" download speed spans at least 3s
// into the past.
#define SPEED_SAMPLE_MIN 150
// The time after which the download starts to be considered "stalled", i.e. the current
// bandwidth is not printed and the recent download speeds are scratched.
#define STALL_START_TIME 5000
// Time between screen refreshes will not be shorter than this.
// NB: In Rufus' case, "screen" means the text overlaid on the progress bar.
#define SCREEN_REFRESH_INTERVAL 200
// Don't refresh the ETA too often to avoid jerkiness in predictions.
// This allows ETA to change approximately once per second.
#define ETA_REFRESH_INTERVAL 990
extern HWND hMultiToolbar, hSaveToolbar, hHashToolbar, hAdvancedDeviceToolbar, hAdvancedFormatToolbar;
extern HFONT hInfoFont;
extern UINT_PTR UM_LANGUAGE_MENU_MAX;
extern BOOL advanced_mode_device, advanced_mode_format, force_large_fat32, app_changed_size;
extern loc_cmd* selected_locale;
extern uint64_t persistence_size;
extern const char *sfd_name, *flash_type[BADLOCKS_PATTERN_TYPES];
extern char *short_image_path, image_option_txt[128];
extern int advanced_device_section_height, advanced_format_section_height, persistence_unit_selection;
extern int selection_default, cbw, ddw, ddbh, bh, update_progress_type;
extern void SetAccessibleName(HWND hCtrl, const char* name);
extern void SetComboEntry(HWND hDlg, int data);
extern void GetBasicControlsWidth(HWND hDlg);
extern void GetMainButtonsWidth(HWND hDlg);
extern void GetHalfDropwdownWidth(HWND hDlg);
extern void GetFullWidth(HWND hDlg);
extern void PositionMainControls(HWND hDlg);
extern void AdjustForLowDPI(HWND hDlg);
extern void SetSectionHeaders(HWND hDlg);
extern void SetPersistencePos(uint64_t pos);
extern void SetPersistenceSize(void);
extern void TogglePersistenceControls(BOOL display);
extern void ToggleAdvancedDeviceOptions(BOOL enable);
extern void ToggleAdvancedFormatOptions(BOOL enable);
extern void ToggleImageOptions(void);
extern void CreateSmallButtons(HWND hDlg);
extern void CreateAdditionalControls(HWND hDlg);
extern void EnableControls(BOOL enable, BOOL remove_checkboxes);
extern void InitProgress(BOOL bOnlyFormat);
extern void ShowLanguageMenu(RECT rcExclude);
extern void SetPassesTooltip(void);
extern void SetBootTypeDropdownWidth(void);
extern void OnPaint(HDC hdc);
| 4,377 |
C
|
.h
| 95 | 44.031579 | 102 | 0.781213 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
4,860 |
vhd.h
|
pbatard_rufus/src/vhd.h
|
/*
* Rufus: The Reliable USB Formatting Utility
* Virtual Disk Handling definitions and prototypes
* Copyright © 2022-2024 Pete Batard <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdint.h>
#include <windows.h>
// Temporary workaround for MinGW32 delay-loading
// See https://github.com/pbatard/rufus/pull/2513
#if defined(__MINGW32__)
#undef DECLSPEC_IMPORT
#define DECLSPEC_IMPORT __attribute__((visibility("hidden")))
#endif
#include <virtdisk.h>
#pragma once
#define WIM_MAGIC 0x0000004D4957534DULL // "MSWIM\0\0\0"
#define WIM_HAS_API_EXTRACT 1
#define WIM_HAS_7Z_EXTRACT 2
#define WIM_HAS_API_APPLY 4
#define WIM_HAS_EXTRACT(r) (r & (WIM_HAS_API_EXTRACT|WIM_HAS_7Z_EXTRACT))
#define SECONDS_SINCE_JAN_1ST_2000 946684800
#define INVALID_CALLBACK_VALUE 0xFFFFFFFF
#define WIM_FLAG_RESERVED 0x00000001
#define WIM_FLAG_VERIFY 0x00000002
#define WIM_FLAG_INDEX 0x00000004
#define WIM_FLAG_NO_APPLY 0x00000008
#define WIM_FLAG_NO_DIRACL 0x00000010
#define WIM_FLAG_NO_FILEACL 0x00000020
#define WIM_FLAG_SHARE_WRITE 0x00000040
#define WIM_FLAG_FILEINFO 0x00000080
#define WIM_FLAG_NO_RP_FIX 0x00000100
// Bitmask for the kind of progress we want to report in the WIM progress callback
#define WIM_REPORT_PROGRESS 0x00000001
#define WIM_REPORT_PROCESS 0x00000002
#define WIM_REPORT_FILEINFO 0x00000004
#define WIM_GENERIC_READ GENERIC_READ
#define WIM_OPEN_EXISTING OPEN_EXISTING
#define WIM_UNDOCUMENTED_BULLSHIT 0x20000000
#define MBR_SIZE 512 // Might need to review this once we see bootable 4k systems
#define VIRTUAL_STORAGE_TYPE_DEVICE_FFU 99
#define CREATE_VIRTUAL_DISK_VERSION_2 2
#define CREATE_VIRTUAL_DISK_FLAG_CREATE_BACKING_STORAGE 8
#ifndef CREATE_VIRTUAL_DISK_PARAMETERS_DEFAULT_BLOCK_SIZE
#define CREATE_VIRTUAL_DISK_PARAMETERS_DEFAULT_BLOCK_SIZE 0
#endif
#ifndef CREATE_VIRTUAL_DISK_PARAMETERS_DEFAULT_SECTOR_SIZE
#define CREATE_VIRTUAL_DISK_PARAMETERS_DEFAULT_SECTOR_SIZE 0
#endif
typedef struct
{
CREATE_VIRTUAL_DISK_VERSION Version;
union
{
struct
{
GUID UniqueId;
ULONGLONG MaximumSize;
ULONG BlockSizeInBytes;
ULONG SectorSizeInBytes;
PCWSTR ParentPath;
PCWSTR SourcePath;
} Version1;
struct
{
GUID UniqueId;
ULONGLONG MaximumSize;
ULONG BlockSizeInBytes;
ULONG SectorSizeInBytes;
ULONG PhysicalSectorSizeInBytes;
PCWSTR ParentPath;
PCWSTR SourcePath;
OPEN_VIRTUAL_DISK_FLAG OpenFlags;
VIRTUAL_STORAGE_TYPE ParentVirtualStorageType;
VIRTUAL_STORAGE_TYPE SourceVirtualStorageType;
GUID ResiliencyGuid;
} Version2;
};
} STOPGAP_CREATE_VIRTUAL_DISK_PARAMETERS;
// From https://docs.microsoft.com/en-us/previous-versions/msdn10/dd834960(v=msdn.10)
// as well as https://msfn.org/board/topic/150700-wimgapi-wimmountimage-progressbar/
enum WIMMessage {
WIM_MSG = WM_APP + 0x1476,
WIM_MSG_TEXT,
WIM_MSG_PROGRESS, // Indicates an update in the progress of an image application.
WIM_MSG_PROCESS, // Enables the caller to prevent a file or a directory from being captured or applied.
WIM_MSG_SCANNING, // Indicates that volume information is being gathered during an image capture.
WIM_MSG_SETRANGE, // Indicates the number of files that will be captured or applied.
WIM_MSG_SETPOS, // Indicates the number of files that have been captured or applied.
WIM_MSG_STEPIT, // Indicates that a file has been either captured or applied.
WIM_MSG_COMPRESS, // Enables the caller to prevent a file resource from being compressed during a capture.
WIM_MSG_ERROR, // Alerts the caller that an error has occurred while capturing or applying an image.
WIM_MSG_ALIGNMENT, // Enables the caller to align a file resource on a particular alignment boundary.
WIM_MSG_RETRY, // Sent when the file is being reapplied because of a network timeout.
WIM_MSG_SPLIT, // Enables the caller to align a file resource on a particular alignment boundary.
WIM_MSG_FILEINFO, // Used in conjunction with WimApplyImages()'s WIM_FLAG_FILEINFO flag to provide detailed file info.
WIM_MSG_INFO, // Sent when an info message is available.
WIM_MSG_WARNING, // Sent when a warning message is available.
WIM_MSG_CHK_PROCESS,
WIM_MSG_SUCCESS = 0,
WIM_MSG_ABORT_IMAGE = -1
};
extern uint8_t WimExtractCheck(BOOL bSilent);
extern BOOL WimExtractFile(const char* wim_image, int index, const char* src, const char* dst, BOOL bSilent);
extern BOOL WimExtractFile_API(const char* image, int index, const char* src, const char* dst, BOOL bSilent);
extern BOOL WimExtractFile_7z(const char* image, int index, const char* src, const char* dst, BOOL bSilent);
extern BOOL WimApplyImage(const char* image, int index, const char* dst);
extern char* WimMountImage(const char* image, int index);
extern BOOL WimUnmountImage(const char* image, int index, BOOL commit);
extern char* WimGetExistingMountPoint(const char* image, int index);
extern BOOL WimIsValidIndex(const char* image, int index);
extern int8_t IsBootableImage(const char* path);
extern char* VhdMountImageAndGetSize(const char* path, uint64_t* disksize);
#define VhdMountImage(path) VhdMountImageAndGetSize(path, NULL)
extern void VhdUnmountImage(void);
extern void VhdSaveImage(void);
extern void IsoSaveImage(void);
| 6,151 |
C
|
.h
| 129 | 45.767442 | 119 | 0.742967 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
4,861 |
mbr_types.h
|
pbatard_rufus/src/mbr_types.h
|
/*
GNU fdisk - a clone of Linux fdisk.
Copyright © 2020 Pete Batard <[email protected]>
Copyright © 2006 Free Software Foundation, Inc.
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, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <inttypes.h>
#pragma once
typedef struct {
const uint8_t type;
const char *name;
} mbr_type_t;
/*
* File system types for MBR partition tables
* See http://en.wikipedia.org/wiki/Partition_type
* Also http://www.win.tue.nl/~aeb/partitions/partition_types-1.html
* Note: If googling APTI (Alternative Partition Table Identification)
* doesn't return squat, then IT ISN'T A REAL THING!!
*/
mbr_type_t mbr_type[] = {
{ 0x00, "Empty" },
{ 0x01, "FAT12" },
{ 0x02, "XENIX root" },
{ 0x03, "XENIX usr" },
{ 0x04, "Small FAT16" },
{ 0x05, "Extended" },
{ 0x06, "FAT16" },
{ 0x07, "NTFS/exFAT/UDF" },
{ 0x08, "AIX" },
{ 0x09, "AIX Bootable" },
{ 0x0a, "OS/2 Boot Manager" },
{ 0x0b, "FAT32" },
{ 0x0c, "FAT32 LBA" },
{ 0x0e, "FAT16 LBA" },
{ 0x0f, "Extended LBA" },
{ 0x10, "OPUS" },
{ 0x11, "Hidden FAT12" },
{ 0x12, "Compaq Diagnostics" },
{ 0x14, "Hidden Small FAT16" },
{ 0x16, "Hidden FAT16" },
{ 0x17, "Hidden NTFS" },
{ 0x18, "AST SmartSleep" },
{ 0x1b, "Hidden FAT32" },
{ 0x1c, "Hidden FAT32 LBA" },
{ 0x1e, "Hidden FAT16 LBA" },
{ 0x20, "Windows Mobile XIP" },
{ 0x21, "SpeedStor" },
{ 0x23, "Windows Mobile XIP" },
{ 0x24, "NEC DOS" },
{ 0x25, "Windows Mobile IMGFS" },
{ 0x27, "Hidden NTFS WinRE" },
{ 0x39, "Plan 9" },
{ 0x3c, "PMagic Recovery" },
{ 0x40, "Venix 80286" },
{ 0x41, "PPC PReP Boot" },
{ 0x42, "SFS" },
{ 0x4d, "QNX4.x" },
{ 0x4e, "QNX4.x" },
{ 0x4f, "QNX4.x" },
{ 0x50, "OnTrack DM" },
{ 0x51, "OnTrack DM" },
{ 0x52, "CP/M" },
{ 0x53, "OnTrack DM" },
{ 0x54, "OnTrack DM" },
{ 0x55, "EZ Drive" },
{ 0x56, "Golden Bow" },
{ 0x5c, "Priam EDisk" },
{ 0x61, "SpeedStor" },
{ 0x63, "GNU HURD/SysV" },
{ 0x64, "Netware" },
{ 0x65, "Netware" },
{ 0x66, "Netware" },
{ 0x67, "Netware" },
{ 0x68, "Netware" },
{ 0x69, "Netware" },
{ 0x70, "DiskSecure MultiBoot" },
{ 0x75, "PC/IX" },
{ 0x77, "Novell" },
{ 0x78, "XOSL" },
{ 0x7e, "F.I.X." },
{ 0x7e, "AODPS" },
{ 0x80, "Minix" },
{ 0x81, "Minix" },
{ 0x82, "GNU/Linux Swap" },
{ 0x83, "GNU/Linux" },
{ 0x84, "Windows Hibernation" },
{ 0x85, "GNU/Linux Extended" },
{ 0x86, "NTFS Volume Set" },
{ 0x87, "NTFS Volume Set" },
{ 0x88, "GNU/Linux Plaintext" },
{ 0x8d, "FreeDOS Hidden FAT12" },
{ 0x8e, "GNU/Linux LVM" },
{ 0x90, "FreeDOS Hidden FAT16" },
{ 0x91, "FreeDOS Hidden Extended" },
{ 0x92, "FreeDOS Hidden FAT16" },
{ 0x93, "GNU/Linux Hidden" },
{ 0x96, "CHRP ISO-9660" },
{ 0x97, "FreeDOS Hidden FAT32" },
{ 0x98, "FreeDOS Hidden FAT32" },
{ 0x9a, "FreeDOS Hidden FAT16" },
{ 0x9b, "FreeDOS Hidden Extended" },
{ 0x9f, "BSD/OS" },
{ 0xa0, "Hibernation" },
{ 0xa1, "Hibernation" },
{ 0xa2, "SpeedStor" },
{ 0xa3, "SpeedStor" },
{ 0xa4, "SpeedStor" },
{ 0xa5, "FreeBSD" },
{ 0xa6, "OpenBSD" },
{ 0xa7, "NeXTSTEP" },
{ 0xa8, "Darwin UFS" },
{ 0xa9, "NetBSD" },
{ 0xab, "Darwin Boot" },
{ 0xaf, "HFS/HFS+" },
{ 0xb0, "BootStar Dummy" },
{ 0xb1, "QNX" },
{ 0xb2, "QNX" },
{ 0xb3, "QNX" },
{ 0xb4, "SpeedStor" },
{ 0xb6, "SpeedStor" },
{ 0xb7, "BSDI" },
{ 0xb8, "BSDI Swap" },
{ 0xbb, "BootWizard Hidden" },
{ 0xbc, "Acronis SZ" },
{ 0xbe, "Solaris Boot" },
{ 0xbf, "Solaris" },
{ 0xc0, "Secured FAT" },
{ 0xc1, "DR DOS FAT12" },
{ 0xc2, "GNU/Linux Hidden" },
{ 0xc3, "GNU/Linux Hidden Swap" },
{ 0xc4, "DR DOS FAT16" },
{ 0xc4, "DR DOS Extended" },
{ 0xc6, "DR DOS FAT16" },
{ 0xc7, "Syrinx" },
{ 0xcd, "ISOHybrid" },
{ 0xda, "Non-FS Data" },
{ 0xdb, "CP/M" },
{ 0xde, "Dell Utility" },
{ 0xdf, "BootIt" },
{ 0xe0, "ST AVFS" },
{ 0xe1, "SpeedStor" },
{ 0xe3, "SpeedStor" },
{ 0xe4, "SpeedStor" },
{ 0xe6, "SpeedStor" },
{ 0xe8, "LUKS" },
{ 0xea, "Rufus Extra" },
{ 0xeb, "BeOS/Haiku" },
{ 0xec, "SkyFS" },
{ 0xed, "GPT Hybrid MBR" },
{ 0xee, "GPT Protective MBR" },
{ 0xef, "EFI System Partition" },
{ 0xf0, "PA-RISC Boot" },
{ 0xf1, "SpeedStor" },
{ 0xf2, "DOS secondary" },
{ 0xf3, "SpeedStor" },
{ 0xf4, "SpeedStor" },
{ 0xf6, "SpeedStor" },
{ 0xfa, "Bochs" },
{ 0xfb, "VMware VMFS" },
{ 0xfc, "VMware VMKCORE" },
{ 0xfd, "GNU/Linux RAID Auto" },
{ 0xfe, "LANstep" },
{ 0xff, "XENIX BBT" },
{ 0, NULL }
};
| 5,007 |
C
|
.h
| 175 | 26.365714 | 77 | 0.607217 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
4,863 |
wue.h
|
pbatard_rufus/src/wue.h
|
/*
* Rufus: The Reliable USB Formatting Utility
* Windows User Experience
* Copyright © 2022 Pete Batard <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <windows.h>
#pragma once
extern int unattend_xml_flags, unattend_xml_mask;
extern int wintogo_index, wininst_index;
extern char* unattend_xml_path;
char* CreateUnattendXml(int arch, int flags);
BOOL ApplyWindowsCustomization(char drive_letter, int flags);
int SetWinToGoIndex(void);
BOOL SetupWinPE(char drive_letter);
BOOL SetupWinToGo(DWORD DriveIndex, const char* drive_name, BOOL use_esp);
BOOL PopulateWindowsVersion(void);
| 1,219 |
C
|
.h
| 29 | 40.310345 | 74 | 0.782462 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
4,864 |
missing.h
|
pbatard_rufus/src/missing.h
|
/*
* Rufus: The Reliable USB Formatting Utility
* Constants and defines missing from various toolchains
* Copyright © 2016-2024 Pete Batard <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <windows.h>
#pragma once
#ifndef MIN
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
#endif
#ifndef MAX
#define MAX(a,b) (((a) > (b)) ? (a) : (b))
#endif
#define LO_ALIGN_X_TO_Y(x, y) (((x) / (y)) * (y))
#define HI_ALIGN_X_TO_Y(x, y) ((((x) + (y) - 1) / (y)) * (y))
#define IS_HEXASCII(c) (((c) >= '0' && (c) <= '9') || ((c) >= 'A' && (c) <= 'F') || ((c) >= 'a' && (c) <= 'f'))
/*
* Prefetch 64 bytes at address m, for read-only operation
* We account for these built-in calls doing nothing if the
* line has already been fetched, or if the address is invalid.
*/
#if defined(__GNUC__) || defined(__clang__)
#define PREFETCH64(m) do { __builtin_prefetch(m, 0, 0); __builtin_prefetch(m+32, 0, 0); } while(0)
#elif defined(_MSC_VER)
#if defined(_M_IX86) || defined (_M_X64)
#define PREFETCH64(m) do { _m_prefetch(m); _m_prefetch(m+32); } while(0)
#else
// _m_prefetch() doesn't seem to exist for MSVC/ARM
#define PREFETCH64(m)
#endif
#endif
/* Read/write with endianness swap */
#if defined (_MSC_VER) && (_MSC_VER >= 1300)
#include <stdlib.h>
#pragma intrinsic(_byteswap_ushort)
#pragma intrinsic(_byteswap_ulong)
#pragma intrinsic(_byteswap_uint64)
#define bswap_uint64 _byteswap_uint64
#define bswap_uint32 _byteswap_ulong
#define bswap_uint16 _byteswap_ushort
#elif defined (__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)))
#define bswap_uint64 __builtin_bswap64
#define bswap_uint32 __builtin_bswap32
#define bswap_uint16 __builtin_bswap16
#endif
#define read_swap16(p) bswap_uint16(*(const uint16_t*)(const uint8_t*)(p))
#define read_swap32(p) bswap_uint32(*(const uint32_t*)(const uint8_t*)(p))
#define read_swap64(p) bswap_uint64(*(const uint64_t*)(const uint8_t*)(p))
#define write_swap16(p,v) (*(uint16_t*)(void*)(p)) = bswap_uint16(v)
#define write_swap32(p,v) (*(uint32_t*)(void*)(p)) = bswap_uint32(v)
#define write_swap64(p,v) (*(uint64_t*)(void*)(p)) = bswap_uint64(v)
/*
* Nibbled from https://github.com/hanji/popcnt/blob/master/populationcount.cpp
* Since MSVC x86_32 and/or ARM don't have intrinsic popcount and I don't have all day
*/
static __inline uint8_t popcnt8(uint8_t val)
{
static const uint8_t nibble_lookup[16] = {
0, 1, 1, 2, 1, 2, 2, 3,
1, 2, 2, 3, 2, 3, 3, 4
};
return nibble_lookup[val & 0x0F] + nibble_lookup[val >> 4];
}
static __inline uint8_t popcnt64(register uint64_t u)
{
u = (u & 0x5555555555555555ULL) + ((u >> 1) & 0x5555555555555555ULL);
u = (u & 0x3333333333333333ULL) + ((u >> 2) & 0x3333333333333333ULL);
u = (u & 0x0f0f0f0f0f0f0f0fULL) + ((u >> 4) & 0x0f0f0f0f0f0f0f0fULL);
u = (u & 0x00ff00ff00ff00ffULL) + ((u >> 8) & 0x00ff00ff00ff00ffULL);
u = (u & 0x0000ffff0000ffffULL) + ((u >> 16) & 0x0000ffff0000ffffULL);
u = (u & 0x00000000ffffffffULL) + ((u >> 32) & 0x00000000ffffffffULL);
return (uint8_t)u;
}
static __inline void *_reallocf(void *ptr, size_t size) {
void *ret = realloc(ptr, size);
if (!ret)
free(ptr);
return ret;
}
static __inline int _log2(register int val)
{
int ret = 0;
if (val < 0)
return -2;
while (val >>= 1)
ret++;
return ret;
}
/// <summary>
/// Remaps bits from a byte according to an 8x8 bit matrix.
/// </summary>
/// <param name="src">The byte to remap.</param>
/// <param name="map">An 8-byte array where each byte has a single bit set to the position to remap to.</param>
/// <param name="reverse">Indicates whether the reverse mapping operation should be applied.</param>
/// <returns>The remapped byte data.</returns>
static __inline uint8_t remap8(uint8_t src, uint8_t* map, const BOOL reverse)
{
uint8_t i, m = 1, r = 0;
for (i = 0, m = 1; i < (sizeof(src) * 8); i++, m <<= 1) {
if (reverse) {
if (src & map[i])
r |= m;
} else {
if (src & m)
r |= map[i];
}
}
return r;
}
/// <summary>
/// Remaps bits from a 16-bit word according to a 16x16 bit matrix.
/// </summary>
/// <param name="src">The word to remap.</param>
/// <param name="map">A 16-word array where each word has a single bit set to the position to remap to.</param>
/// <param name="reverse">Indicates whether the reverse mapping operation should be applied.</param>
/// <returns>The remapped byte data.</returns>
static __inline uint16_t remap16(uint16_t src, uint16_t* map, const BOOL reverse)
{
uint16_t i, m = 1, r = 0;
for (i = 0, m = 1; i < (sizeof(src) * 8); i++, m <<= 1) {
if (reverse) {
if (src & map[i])
r |= m;
} else {
if (src & m)
r |= map[i];
}
}
return r;
}
/* Why oh why does Microsoft have to make everybody suffer with their braindead use of Unicode? */
#define _RT_ICON MAKEINTRESOURCEA(3)
#define _RT_DIALOG MAKEINTRESOURCEA(5)
#define _RT_RCDATA MAKEINTRESOURCEA(10)
#define _RT_GROUP_ICON MAKEINTRESOURCEA((ULONG_PTR)(MAKEINTRESOURCEA(3) + 11))
/* MinGW doesn't know these */
#ifndef WM_CLIENTSHUTDOWN
#define WM_CLIENTSHUTDOWN 0x3B
#endif
#ifndef WM_COPYGLOBALDATA
#define WM_COPYGLOBALDATA 0x49
#endif
#ifndef INTERNET_OPTION_ENABLE_HTTP_PROTOCOL
#define INTERNET_OPTION_ENABLE_HTTP_PROTOCOL 148
#endif
#ifndef INTERNET_OPTION_HTTP_DECODING
#define INTERNET_OPTION_HTTP_DECODING 65
#endif
#ifndef HTTP_PROTOCOL_FLAG_HTTP2
#define HTTP_PROTOCOL_FLAG_HTTP2 2
#endif
#ifndef ERROR_OFFSET_ALIGNMENT_VIOLATION
#define ERROR_OFFSET_ALIGNMENT_VIOLATION 327
#endif
/* RISC-V is still bleeding edge */
#ifndef IMAGE_FILE_MACHINE_RISCV32
#define IMAGE_FILE_MACHINE_RISCV32 0x5032
#endif
#ifndef IMAGE_FILE_MACHINE_RISCV64
#define IMAGE_FILE_MACHINE_RISCV64 0x5064
#endif
#ifndef IMAGE_FILE_MACHINE_RISCV128
#define IMAGE_FILE_MACHINE_RISCV128 0x5128
#endif
| 6,429 |
C
|
.h
| 177 | 34.762712 | 111 | 0.684042 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
4,865 |
dos.h
|
pbatard_rufus/src/dos.h
|
/*
* Rufus: The Reliable USB Formatting Utility
* MS-DOS boot file extraction, from the FAT12 floppy image in diskcopy.dll
* Copyright © 2011-2013 Pete Batard <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* http://www.c-jump.com/CIS24/Slides/FAT/lecture.html
Ideally, we'd read the following from the FAT Boot Sector, but we have
a pretty good idea of what they are for a 1.44 MB floppy image */
#define FAT12_ROOTDIR_OFFSET 0x2600
#define FAT12_CLUSTER_SIZE 0x200 // = sector size
#define FAT12_DATA_START 0x4200
#define FAT12_CLUSTER_OFFSET ((FAT12_DATA_START/FAT12_CLUSTER_SIZE)-2) // First cluster in data area is #2
/*
* Lifted from ReactOS:
* http://reactos-mirror.googlecode.com/svn/trunk/reactos/drivers/filesystems/fastfat_new/fat.h
*/
#pragma pack(push, 1) // You *DO* want packed structs here
//
// Directory Structure:
//
typedef struct _FAT_TIME
{
union {
struct {
USHORT DoubleSeconds : 5;
USHORT Minute : 6;
USHORT Hour : 5;
};
USHORT Value;
};
} FAT_TIME, *PFAT_TIME;
//
//
//
typedef struct _FAT_DATE {
union {
struct {
USHORT Day : 5;
USHORT Month : 4;
/* Relative to 1980 */
USHORT Year : 7;
};
USHORT Value;
};
} FAT_DATE, *PFAT_DATE;
//
//
//
typedef struct _FAT_DATETIME {
union {
struct {
FAT_TIME Time;
FAT_DATE Date;
};
ULONG Value;
};
} FAT_DATETIME, *PFAT_DATETIME;
//
//
//
typedef struct _DIR_ENTRY
{
UCHAR FileName[11];
UCHAR Attributes;
UCHAR Case;
UCHAR CreationTimeTenMs;
FAT_DATETIME CreationDateTime;
FAT_DATE LastAccessDate;
union {
USHORT ExtendedAttributes;
USHORT FirstClusterOfFileHi;
};
FAT_DATETIME LastWriteDateTime;
USHORT FirstCluster;
ULONG FileSize;
} DIR_ENTRY, *PDIR_ENTRY;
// sizeof = 0x020
typedef struct _LONG_FILE_NAME_ENTRY {
UCHAR SeqNum;
UCHAR NameA[10];
UCHAR Attributes;
UCHAR Type;
UCHAR Checksum;
USHORT NameB[6];
USHORT Reserved;
USHORT NameC[2];
} LONG_FILE_NAME_ENTRY, *PLONG_FILE_NAME_ENTRY;
// sizeof = 0x020
#pragma pack(pop)
#define FAT_LFN_NAME_LENGTH \
(RTL_FIELD_SIZE(LONG_FILE_NAME_ENTRY, NameA) \
+ RTL_FIELD_SIZE(LONG_FILE_NAME_ENTRY, NameB) \
+ RTL_FIELD_SIZE(LONG_FILE_NAME_ENTRY, NameC))
#define FAT_FN_DIR_ENTRY_LAST 0x40
#define FAT_FN_MAX_DIR_ENTIES 0x14
#define FAT_BYTES_PER_DIRENT 0x20
#define FAT_BYTES_PER_DIRENT_LOG 0x05
#define FAT_DIRENT_NEVER_USED 0x00
#define FAT_DIRENT_REALLY_0E5 0x05
#define FAT_DIRENT_DIRECTORY_ALIAS 0x2e
#define FAT_DIRENT_DELETED 0xe5
#define FAT_CASE_LOWER_BASE 0x08
#define FAT_CASE_LOWER_EXT 0x10
#define FAT_DIRENT_ATTR_READ_ONLY 0x01
#define FAT_DIRENT_ATTR_HIDDEN 0x02
#define FAT_DIRENT_ATTR_SYSTEM 0x04
#define FAT_DIRENT_ATTR_VOLUME_ID 0x08
#define FAT_DIRENT_ATTR_DIRECTORY 0x10
#define FAT_DIRENT_ATTR_ARCHIVE 0x20
#define FAT_DIRENT_ATTR_DEVICE 0x40
#define FAT_DIRENT_ATTR_LFN (FAT_DIRENT_ATTR_READ_ONLY | \
FAT_DIRENT_ATTR_HIDDEN | \
FAT_DIRENT_ATTR_SYSTEM | \
FAT_DIRENT_ATTR_VOLUME_ID)
extern BOOL SetDOSLocale(const char* path, BOOL bFreeDOS);
| 4,149 |
C
|
.h
| 128 | 27.648438 | 113 | 0.649289 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,869 |
smart.h
|
pbatard_rufus/src/smart.h
|
/*
* Rufus: The Reliable USB Formatting Utility
* SMART HDD vs Flash detection (using ATA over USB, S.M.A.R.T., etc.)
* Copyright © 2013-2014 Pete Batard <[email protected]>
*
* Based in part on Smartmontools: http://smartmontools.sourceforge.net
* Copyright © 2006-12 Douglas Gilbert <[email protected]>
* Copyright © 2009-13 Christian Franke <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// From http://stackoverflow.com/a/9284679
#define COMPILE_TIME_ASSERT(pred) switch(0) {case 0: case pred:;}
// Official commands
#define ATA_DATA_SET_MANAGEMENT 0x06 // TRIM command for SSDs
#define ATA_READ_LOG_EXT 0x2f
#define ATA_CHECK_POWER_MODE 0xe5
#define ATA_IDENTIFY_DEVICE 0xec
#define ATA_IDENTIFY_PACKET_DEVICE 0xa1
#define ATA_IDLE 0xe3
#define ATA_SMART_CMD 0xb0
#define ATA_SECURITY_FREEZE_LOCK 0xf5
#define ATA_SET_FEATURES 0xef
#define ATA_STANDBY_IMMEDIATE 0xe0
#define SAT_ATA_PASSTHROUGH_12 0xa1
// Non official pseudo commands
#define USB_CYPRESS_ATA_PASSTHROUGH 0x24
#define USB_JMICRON_ATA_PASSTHROUGH 0xdf
#define USB_SUNPLUS_ATA_PASSTHROUGH 0xf8
// SMART ATA Subcommands
// Also see https://github.com/gregkh/ndas/blob/master/udev.c
#define ATA_SMART_READ_VALUES 0xd0
#define ATA_SMART_READ_THRESHOLDS 0xd1
#define ATA_SMART_AUTOSAVE 0xd2
#define ATA_SMART_SAVE 0xd3
#define ATA_SMART_IMMEDIATE_OFFLINE 0xd4
#define ATA_SMART_READ_LOG_SECTOR 0xd5
#define ATA_SMART_WRITE_LOG_SECTOR 0xd6
#define ATA_SMART_WRITE_THRESHOLDS 0xd7
#define ATA_SMART_ENABLE 0xd8
#define ATA_SMART_DISABLE 0xd9
#define ATA_SMART_STATUS 0xda
#define SCSI_IOCTL_DATA_OUT 0
#define SCSI_IOCTL_DATA_IN 1
#define SCSI_IOCTL_DATA_UNSPECIFIED 2
#define ATA_PASSTHROUGH_DATA_OUT SCSI_IOCTL_DATA_OUT
#define ATA_PASSTHROUGH_DATA_IN SCSI_IOCTL_DATA_IN
#define ATA_PASSTHROUGH_DATA_NONE SCSI_IOCTL_DATA_UNSPECIFIED
// Status codes returned by ScsiPassthroughDirect()
#define SPT_SUCCESS 0
#define SPT_ERROR_CDB_LENGTH -1
#define SPT_ERROR_BUFFER -2
#define SPT_ERROR_DIRECTION -3
#define SPT_ERROR_EXTENDED_CDB -4
#define SPT_ERROR_CDB_OPCODE -5
#define SPT_ERROR_TIMEOUT -6
#define SPT_ERROR_INVALID_PARAMETER -7
#define SPT_ERROR_CHECK_STATUS -8
#define SPT_ERROR_UNKNOWN_ERROR -99
#define SPT_CDB_LENGTH 16
#define SPT_SENSE_LENGTH 32
#define SPT_TIMEOUT_VALUE 2 // In seconds
#define SECTOR_SIZE_SHIFT_BIT 9 // We use 512 bytes sectors always
#define IOCTL_SCSI_BASE FILE_DEVICE_CONTROLLER
#define IOCTL_SCSI_PASS_THROUGH \
CTL_CODE(IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
#define IOCTL_SCSI_PASS_THROUGH_DIRECT \
CTL_CODE(IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
typedef struct {
USHORT Length;
UCHAR ScsiStatus;
UCHAR PathId;
UCHAR TargetId;
UCHAR Lun;
UCHAR CdbLength;
UCHAR SenseInfoLength;
UCHAR DataIn;
ULONG DataTransferLength;
ULONG TimeOutValue;
ULONG_PTR DataBufferOffset;
ULONG SenseInfoOffset;
UCHAR Cdb[SPT_CDB_LENGTH];
} SCSI_PASS_THROUGH;
typedef struct {
USHORT Length;
UCHAR ScsiStatus;
UCHAR PathId;
UCHAR TargetId;
UCHAR Lun;
UCHAR CdbLength;
UCHAR SenseInfoLength;
UCHAR DataIn;
ULONG DataTransferLength;
ULONG TimeOutValue;
PVOID DataBuffer;
ULONG SenseInfoOffset;
UCHAR Cdb[SPT_CDB_LENGTH];
} SCSI_PASS_THROUGH_DIRECT;
typedef struct {
SCSI_PASS_THROUGH_DIRECT sptd;
ULONG Align;
UCHAR SenseBuf[SPT_SENSE_LENGTH];
} SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
// Custom ATA over USB command
typedef struct {
uint8_t AtaCmd; // eg: ATA_SMART_CMD = 0xb0, IDENTIFY = 0xec, etc.
uint8_t Features; // SMART subcommand, eg: SMART_ENABLE_OPS = 0xd8, etc.
uint8_t Device; // 0x00 for Identify, 0xA0, 0xB0 for JMicron/SAT SMART ops
uint8_t Align;
uint8_t Lba_low; // LBA
uint8_t Lba_mid;
uint8_t Lba_high;
uint8_t Lba_unused;
} ATA_PASSTHROUGH_CMD;
typedef BOOL (*AtaPassthroughFn_t)(
HANDLE hPhysical,
ATA_PASSTHROUGH_CMD* Command,
void* DataBuffer,
size_t BufLen,
uint32_t Timeout
);
typedef struct {
AtaPassthroughFn_t fn;
const char* type;
} AtaPassThroughType;
// From http://msdn.microsoft.com/en-us/library/windows/hardware/ff559006.aspx
#pragma pack(1) // Packed as the size must be 512 bytes exactly
typedef struct _IDENTIFY_DEVICE_DATA {
struct {
USHORT Reserved1 :1;
USHORT Retired3 :1;
USHORT ResponseIncomplete :1;
USHORT Retired2 :3;
USHORT FixedDevice :1;
USHORT RemovableMedia :1;
USHORT Retired1 :7;
USHORT DeviceType :1;
} GeneralConfiguration;
USHORT NumCylinders;
USHORT ReservedWord2;
USHORT NumHeads;
USHORT Retired1[2];
USHORT NumSectorsPerTrack;
USHORT VendorUnique1[3];
UCHAR SerialNumber[20];
USHORT Retired2[2];
USHORT Obsolete1;
UCHAR FirmwareRevision[8];
UCHAR ModelNumber[40];
UCHAR MaximumBlockTransfer;
UCHAR VendorUnique2;
USHORT ReservedWord48;
struct {
UCHAR ReservedByte49;
UCHAR DmaSupported :1;
UCHAR LbaSupported :1;
UCHAR IordyDisable :1;
UCHAR IordySupported :1;
UCHAR Reserved1 :1;
UCHAR StandybyTimerSupport :1;
UCHAR Reserved2 :2;
USHORT ReservedWord50;
} Capabilities;
USHORT ObsoleteWords51[2];
USHORT TranslationFieldsValid :3;
USHORT Reserved3 :13;
USHORT NumberOfCurrentCylinders;
USHORT NumberOfCurrentHeads;
USHORT CurrentSectorsPerTrack;
ULONG CurrentSectorCapacity;
UCHAR CurrentMultiSectorSetting;
UCHAR MultiSectorSettingValid :1;
UCHAR ReservedByte59 :7;
ULONG UserAddressableSectors;
USHORT ObsoleteWord62;
USHORT MultiWordDMASupport :8;
USHORT MultiWordDMAActive :8;
USHORT AdvancedPIOModes :8;
USHORT ReservedByte64 :8;
USHORT MinimumMWXferCycleTime;
USHORT RecommendedMWXferCycleTime;
USHORT MinimumPIOCycleTime;
USHORT MinimumPIOCycleTimeIORDY;
USHORT ReservedWords69[6];
USHORT QueueDepth :5;
USHORT ReservedWord75 :11;
USHORT ReservedWords76[4];
USHORT MajorRevision;
USHORT MinorRevision;
struct {
USHORT SmartCommands :1;
USHORT SecurityMode :1;
USHORT RemovableMediaFeature :1;
USHORT PowerManagement :1;
USHORT Reserved1 :1;
USHORT WriteCache :1;
USHORT LookAhead :1;
USHORT ReleaseInterrupt :1;
USHORT ServiceInterrupt :1;
USHORT DeviceReset :1;
USHORT HostProtectedArea :1;
USHORT Obsolete1 :1;
USHORT WriteBuffer :1;
USHORT ReadBuffer :1;
USHORT Nop :1;
USHORT Obsolete2 :1;
USHORT DownloadMicrocode :1;
USHORT DmaQueued :1;
USHORT Cfa :1;
USHORT AdvancedPm :1;
USHORT Msn :1;
USHORT PowerUpInStandby :1;
USHORT ManualPowerUp :1;
USHORT Reserved2 :1;
USHORT SetMax :1;
USHORT Acoustics :1;
USHORT BigLba :1;
USHORT DeviceConfigOverlay :1;
USHORT FlushCache :1;
USHORT FlushCacheExt :1;
USHORT Resrved3 :2;
USHORT SmartErrorLog :1;
USHORT SmartSelfTest :1;
USHORT MediaSerialNumber :1;
USHORT MediaCardPassThrough :1;
USHORT StreamingFeature :1;
USHORT GpLogging :1;
USHORT WriteFua :1;
USHORT WriteQueuedFua :1;
USHORT WWN64Bit :1;
USHORT URGReadStream :1;
USHORT URGWriteStream :1;
USHORT ReservedForTechReport :2;
USHORT IdleWithUnloadFeature :1;
USHORT Reserved4 :2;
} CommandSetSupport;
struct {
USHORT SmartCommands :1;
USHORT SecurityMode :1;
USHORT RemovableMediaFeature :1;
USHORT PowerManagement :1;
USHORT Reserved1 :1;
USHORT WriteCache :1;
USHORT LookAhead :1;
USHORT ReleaseInterrupt :1;
USHORT ServiceInterrupt :1;
USHORT DeviceReset :1;
USHORT HostProtectedArea :1;
USHORT Obsolete1 :1;
USHORT WriteBuffer :1;
USHORT ReadBuffer :1;
USHORT Nop :1;
USHORT Obsolete2 :1;
USHORT DownloadMicrocode :1;
USHORT DmaQueued :1;
USHORT Cfa :1;
USHORT AdvancedPm :1;
USHORT Msn :1;
USHORT PowerUpInStandby :1;
USHORT ManualPowerUp :1;
USHORT Reserved2 :1;
USHORT SetMax :1;
USHORT Acoustics :1;
USHORT BigLba :1;
USHORT DeviceConfigOverlay :1;
USHORT FlushCache :1;
USHORT FlushCacheExt :1;
USHORT Resrved3 :2;
USHORT SmartErrorLog :1;
USHORT SmartSelfTest :1;
USHORT MediaSerialNumber :1;
USHORT MediaCardPassThrough :1;
USHORT StreamingFeature :1;
USHORT GpLogging :1;
USHORT WriteFua :1;
USHORT WriteQueuedFua :1;
USHORT WWN64Bit :1;
USHORT URGReadStream :1;
USHORT URGWriteStream :1;
USHORT ReservedForTechReport :2;
USHORT IdleWithUnloadFeature :1;
USHORT Reserved4 :2;
} CommandSetActive;
USHORT UltraDMASupport :8;
USHORT UltraDMAActive :8;
USHORT ReservedWord89[4];
USHORT HardwareResetResult;
USHORT CurrentAcousticValue :8;
USHORT RecommendedAcousticValue :8;
USHORT ReservedWord95[5];
ULONG Max48BitLBA[2];
USHORT StreamingTransferTime;
USHORT ReservedWord105;
struct {
USHORT LogicalSectorsPerPhysicalSector :4;
USHORT Reserved0 :8;
USHORT LogicalSectorLongerThan256Words :1;
USHORT MultipleLogicalSectorsPerPhysicalSector :1;
USHORT Reserved1 :2;
} PhysicalLogicalSectorSize;
USHORT InterSeekDelay;
USHORT WorldWideName[4];
USHORT ReservedForWorldWideName128[4];
USHORT ReservedForTlcTechnicalReport;
USHORT WordsPerLogicalSector[2];
struct {
USHORT ReservedForDrqTechnicalReport :1;
USHORT WriteReadVerifySupported :1;
USHORT Reserved01 :11;
USHORT Reserved1 :2;
} CommandSetSupportExt;
struct {
USHORT ReservedForDrqTechnicalReport :1;
USHORT WriteReadVerifyEnabled :1;
USHORT Reserved01 :11;
USHORT Reserved1 :2;
} CommandSetActiveExt;
USHORT ReservedForExpandedSupportandActive[6];
USHORT MsnSupport :2;
USHORT ReservedWord1274 :14;
struct {
USHORT SecuritySupported :1;
USHORT SecurityEnabled :1;
USHORT SecurityLocked :1;
USHORT SecurityFrozen :1;
USHORT SecurityCountExpired :1;
USHORT EnhancedSecurityEraseSupported :1;
USHORT Reserved0 :2;
USHORT SecurityLevel :1;
USHORT Reserved1 :7;
} SecurityStatus;
USHORT ReservedWord129[31];
struct {
USHORT MaximumCurrentInMA2 :12;
USHORT CfaPowerMode1Disabled :1;
USHORT CfaPowerMode1Required :1;
USHORT Reserved0 :1;
USHORT Word160Supported :1;
} CfaPowerModel;
USHORT ReservedForCfaWord161[8];
struct {
USHORT SupportsTrim :1;
USHORT Reserved0 :15;
} DataSetManagementFeature;
USHORT ReservedForCfaWord170[6];
USHORT CurrentMediaSerialNumber[30];
USHORT ReservedWord206;
USHORT ReservedWord207[2];
struct {
USHORT AlignmentOfLogicalWithinPhysical :14;
USHORT Word209Supported :1;
USHORT Reserved0 :1;
} BlockAlignment;
USHORT WriteReadVerifySectorCountMode3Only[2];
USHORT WriteReadVerifySectorCountMode2Only[2];
struct {
USHORT NVCachePowerModeEnabled :1;
USHORT Reserved0 :3;
USHORT NVCacheFeatureSetEnabled :1;
USHORT Reserved1 :3;
USHORT NVCachePowerModeVersion :4;
USHORT NVCacheFeatureSetVersion :4;
} NVCacheCapabilities;
USHORT NVCacheSizeLSW;
USHORT NVCacheSizeMSW;
USHORT NominalMediaRotationRate;
USHORT ReservedWord218;
struct {
UCHAR NVCacheEstimatedTimeToSpinUpInSeconds;
UCHAR Reserved;
} NVCacheOptions;
USHORT ReservedWord220[35];
USHORT Signature :8;
USHORT CheckSum :8;
} IDENTIFY_DEVICE_DATA, *PIDENTIFY_DEVICE_DATA;
#pragma pack()
| 12,033 |
C
|
.h
| 387 | 28.857881 | 89 | 0.757138 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,872 |
settings.h
|
pbatard_rufus/src/settings.h
|
/*
* Rufus: The Reliable USB Formatting Utility
* Settings access, through either registry or INI file
* Copyright © 2015-2024 Pete Batard <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <windows.h>
#include <stdint.h>
#include "rufus.h"
#include "msapi_utf8.h"
#include "registry.h"
#pragma once
extern char* ini_file;
/*
* List of setting names used by this application
*/
#define SETTING_ADVANCED_MODE "AdvancedMode"
#define SETTING_ADVANCED_MODE_DEVICE "ShowAdvancedDriveProperties"
#define SETTING_ADVANCED_MODE_FORMAT "ShowAdvancedFormatOptions"
#define SETTING_COMM_CHECK "CommCheck64"
#define SETTING_DEFAULT_THREAD_PRIORITY "DefaultThreadPriority"
#define SETTING_DISABLE_FAKE_DRIVES_CHECK "DisableFakeDrivesCheck"
#define SETTING_DISABLE_LGP "DisableLGP"
#define SETTING_DISABLE_RUFUS_MBR "DisableRufusMBR"
#define SETTING_DISABLE_SECURE_BOOT_NOTICE "DisableSecureBootNotice"
#define SETTING_DISABLE_VHDS "DisableVHDs"
#define SETTING_ENABLE_EXTRA_HASHES "EnableExtraHashes"
#define SETTING_ENABLE_FILE_INDEXING "EnableFileIndexing"
#define SETTING_ENABLE_RUNTIME_VALIDATION "EnableRuntimeValidation"
#define SETTING_ENABLE_USB_DEBUG "EnableUsbDebug"
#define SETTING_ENABLE_VMDK_DETECTION "EnableVmdkDetection"
#define SETTING_ENABLE_WIN_DUAL_EFI_BIOS "EnableWindowsDualUefiBiosMode"
#define SETTING_EXPERT_MODE "ExpertMode"
#define SETTING_FORCE_LARGE_FAT32_FORMAT "ForceLargeFat32Formatting"
#define SETTING_IGNORE_BOOT_MARKER "IgnoreBootMarker"
#define SETTING_INCLUDE_BETAS "CheckForBetas"
#define SETTING_LAST_UPDATE "LastUpdateCheck"
#define SETTING_LOCALE "Locale"
#define SETTING_UPDATE_INTERVAL "UpdateCheckInterval"
#define SETTING_USE_EXT_VERSION "UseExtVersion"
#define SETTING_USE_PROPER_SIZE_UNITS "UseProperSizeUnits"
#define SETTING_USE_UDF_VERSION "UseUdfVersion"
#define SETTING_USE_VDS "UseVds"
#define SETTING_PERSISTENT_LOG "PersistentLog"
#define SETTING_PREFERRED_SAVE_IMAGE_TYPE "PreferredSaveImageType"
#define SETTING_PRESERVE_TIMESTAMPS "PreserveTimestamps"
#define SETTING_VERBOSE_UPDATES "VerboseUpdateCheck"
#define SETTING_WUE_OPTIONS "WindowsUserExperienceOptions"
static __inline BOOL CheckIniKey(const char* key) {
char* str = get_token_data_file(key, ini_file);
BOOL ret = (str != NULL);
safe_free(str);
return ret;
}
#define CheckIniKey64 CheckIniKey
#define CheckIniKey32 CheckIniKey
#define CheckIniKeyBool CheckIniKey
#define CheckIniKeyStr CheckIniKey
static __inline int64_t ReadIniKey64(const char* key) {
int64_t val = 0;
char* str = get_token_data_file(key, ini_file);
if (str != NULL) {
val = _strtoi64(str, NULL, 0);
free(str);
}
return val;
}
static __inline BOOL WriteIniKey64(const char* key, int64_t val) {
char str[24];
static_sprintf(str, "%" PRIi64, val);
return (set_token_data_file(key, str, ini_file) != NULL);
}
static __inline int32_t ReadIniKey32(const char* key) {
int32_t val = 0;
char* str = get_token_data_file(key, ini_file);
if (str != NULL) {
val = strtol(str, NULL, 0);
free(str);
}
return val;
}
static __inline BOOL WriteIniKey32(const char* key, int32_t val) {
char str[12];
static_sprintf(str, "%d", val);
return (set_token_data_file(key, str, ini_file) != NULL);
}
static __inline char* ReadIniKeyStr(const char* key) {
static char str[512];
char* val;
str[0] = 0;
val = get_token_data_file(key, ini_file);
if (val != NULL) {
static_strcpy(str, val);
free(val);
}
return str;
}
static __inline BOOL WriteIniKeyStr(const char* key, const char* val) {
return (set_token_data_file(key, val, ini_file) != NULL);
}
/* Helpers for boolean operations */
#define ReadIniKeyBool(key) (ReadIniKey32(key) != 0)
#define WriteIniKeyBool(key, b) WriteIniKey32(key, (b)?1:0)
/*
* Read and store settings from/to ini file or registry
*/
static __inline int64_t ReadSetting64(const char* key) {
return (ini_file != NULL)?ReadIniKey64(key):ReadRegistryKey64(REGKEY_HKCU, key);
}
static __inline BOOL WriteSetting64(const char* key, int64_t val) {
return (ini_file != NULL)?WriteIniKey64(key, val):WriteRegistryKey64(REGKEY_HKCU, key, val);
}
static __inline int32_t ReadSetting32(const char* key) {
return (ini_file != NULL)?ReadIniKey32(key):ReadRegistryKey32(REGKEY_HKCU, key);
}
static __inline BOOL WriteSetting32(const char* key, int32_t val) {
return (ini_file != NULL)?WriteIniKey32(key, val):WriteRegistryKey32(REGKEY_HKCU, key, val);
}
static __inline BOOL ReadSettingBool(const char* key) {
return (ini_file != NULL)?ReadIniKeyBool(key):ReadRegistryKeyBool(REGKEY_HKCU, key);
}
static __inline BOOL WriteSettingBool(const char* key, BOOL val) {
return (ini_file != NULL)?WriteIniKeyBool(key, val):WriteRegistryKeyBool(REGKEY_HKCU, key, val);
}
static __inline char* ReadSettingStr(const char* key) {
return (ini_file != NULL)?ReadIniKeyStr(key):ReadRegistryKeyStr(REGKEY_HKCU, key);
}
static __inline BOOL WriteSettingStr(const char* key, char* val) {
return (ini_file != NULL)?WriteIniKeyStr(key, val):WriteRegistryKeyStr(REGKEY_HKCU, key, val);
}
| 5,940 |
C
|
.h
| 142 | 40.274648 | 97 | 0.729786 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
4,874 |
hdd_vs_ufd.h
|
pbatard_rufus/src/hdd_vs_ufd.h
|
/*
* Rufus: The Reliable USB Formatting Utility
* SMART HDD vs Flash detection - isHDD() tables
* Copyright © 2013-2023 Pete Batard <[email protected]>
*
* Based in part on drivedb.h from Smartmontools:
* http://svn.code.sf.net/p/smartmontools/code/trunk/smartmontools/drivedb.h
* Copyright © 2003-11 Philip Williams, Bruce Allen
* Copyright © 2008-13 Christian Franke <[email protected]>
*
* Also based on entries listed in the identification flash database
* (http://flashboot.ru/iflash/saved/) as well as the Linux USB IDs
* (http://www.linux-usb.org/usb.ids)
*
* 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/>.
*/
#pragma once
#include <stdint.h>
/*
* A positive score means HDD, a negative one an UFD
* The higher the absolute value, the greater the probability
*/
typedef struct {
const char* name;
const int score;
} str_score_t;
typedef struct {
const uint16_t vid;
const int score;
} vid_score_t;
typedef struct {
const uint16_t vid;
const uint16_t pid;
const int score;
} vidpid_score_t;
/* String identifiers:
* Some info comes from http://knowledge.seagate.com/articles/en_US/FAQ/204763en,
* other http://svn.code.sf.net/p/smartmontools/code/trunk/smartmontools/drivedb.h
* '#' means any number in [0-9]
*/
static str_score_t str_score[] = {
{ "IC#", 10 },
{ "ST#", 10 },
{ "MX#", 10 },
{ "WDC", 10 },
{ "IBM", 10 },
{ "STM#", 10 },
{ "HDS#", 10 }, // These Hitachi drives are a PITA
{ "HDP#", 10 },
{ "HDT#", 10 },
{ "HTE#", 10 },
{ "HTS#", 10 },
{ "HUA#", 10 },
{ "APPLE", 10 },
{ "INTEL", 10 },
{ "MAXTOR", 10 },
{ "HITACHI", 10 },
{ "SEAGATE", 10 },
{ "SAMSUNG", 5 },
{ "FUJITSU", 10 },
{ "TOSHIBA", 5 },
{ "QUANTUM", 10 },
{ "EXCELSTOR", 10 },
{ "CORSAIR", -15 },
{ "KINGMAX", -15 },
{ "KINGSTON", -15 },
{ "LEXAR", -15 },
{ "MUSHKIN", -15 },
{ "PNY", -15 },
{ "SANDISK", -15 },
{ "TRANSCEND", -15 },
};
static str_score_t str_adjust[] = {
{ "Gadget", -10 },
{ "Flash", -10 },
{ "SD-CARD", -10 },
{ "uSD Card", -10 },
{ "HDD", +20 },
{ "SATA", +20 },
{ "SCSI", +20 },
{ "SSD", +20 }
};
/* The lists belows set a score according to VID & VID:PID
* These were constructed as follows:
* 1. Pick all the VID:PIDs from http://svn.code.sf.net/p/smartmontools/code/trunk/smartmontools/drivedb.h
* 2. Check that VID against http://flashboot.ru/iflash/saved/ as well as http://www.linux-usb.org/usb.ids
* 3. If a lot of flash or card reader devices are returned, add the VID:PID, with a positive score,
* in the vidpid table (so that the default will be UFD, and HDD the exception)
* 4. If only a few flash devices are returned, add the VID to our list with a positive score and
* add the flash entries in the VID:PID list with a negative score
* 5. Add common UFD providers from http://flashboot.ru/iflash/saved/ with a negative score
* These lists MUST be kept in increasing VID/VID:PID order
*/
static vid_score_t vid_score[] = {
{ 0x0011, -5 }, // Kingston
{ 0x03f0, -5 }, // HP
{ 0x0409, -10 }, // NEC/Toshiba
{ 0x0411, 5 }, // Buffalo
{ 0x0420, -5 }, // Chipsbank
{ 0x046d, -5 }, // Logitech
{ 0x0480, 5 }, // Toshiba
{ 0x048d, -10 }, // ITE
{ 0x04b4, 10 }, // Cypress
{ 0x04c5, 7 }, // Fujitsu
{ 0x04e8, 5 }, // Samsung
{ 0x04f3, -5 }, // Elan
{ 0x04fc, 5 }, // Sunplus
{ 0x056e, -5 }, // Elecom
{ 0x058f, -5 }, // Alcor
{ 0x059b, 7 }, // Iomega
{ 0x059f, 5 }, // LaCie
{ 0x05ab, 10 }, // In-System Design
{ 0x05dc, -5 }, // Lexar
{ 0x05e3, -5 }, // Genesys Logic
{ 0x067b, 7 }, // Prolific
{ 0x0718, -2 }, // Imation
{ 0x0781, -5 }, // SanDisk
{ 0x07ab, 8 }, // Freecom
{ 0x090c, -5 }, // Silicon Motion (also used by Samsung)
{ 0x0928, 10 }, // PLX Technology
{ 0x0930, -8 }, // Toshiba
{ 0x093a, -5 }, // Pixart
{ 0x0951, -5 }, // Kingston
{ 0x09da, -5 }, // A4 Tech
{ 0x0b27, -5 }, // Ritek
{ 0x0bc2, 10 }, // Seagate
{ 0x0bda, -10 }, // Realtek
{ 0x0c76, -5 }, // JMTek
{ 0x0cf2, -5 }, // ENE
{ 0x0d49, 10 }, // Maxtor
{ 0x0dc4, 10 }, // Macpower Peripherals
{ 0x1000, -5 }, // Speed Tech
{ 0x1002, -5 }, // Hisun
{ 0x1005, -5 }, // Apacer
{ 0x1043, -5 }, // iCreate
{ 0x1058, 10 }, // Western Digital
{ 0x1221, -5 }, // Kingston (?)
{ 0x12d1, -5 }, // Huawei
{ 0x125f, -5 }, // Adata
{ 0x1307, -5 }, // USBest
{ 0x13fd, 10 }, // Initio
{ 0x13fe, -5 }, // Kingston
{ 0x14cd, -5 }, // Super Top
{ 0x1516, -5 }, // CompUSA
{ 0x152d, 10 }, // JMicron
{ 0x1687, -5 }, // Kingmax
{ 0x174c, 3 }, // ASMedia (also used by SanDisk)
{ 0x1759, 8 }, // LucidPort
{ 0x18a5, -2 }, // Verbatim
{ 0x18ec, -5 }, // Arkmicro
{ 0x1908, -5 }, // Ax216
{ 0x1a4a, 10 }, // Silicon Image
{ 0x1b1c, -5 }, // Corsair
{ 0x1e3d, -5 }, // Chipsbank
{ 0x1f75, -2 }, // Innostor
{ 0x2001, -5 }, // Micov
{ 0x201e, -5 }, // Evdo
{ 0x2109, 10 }, // VIA Labs
{ 0x2188, -5 }, // SMI
{ 0x3538, -5 }, // PQI
{ 0x413c, -5 }, // Ameco
{ 0x4971, 10 }, // Hitachi
{ 0x5136, -5 }, // Skymedi
{ 0x8564, -5 }, // Transcend
{ 0x8644, -5 }, // NandTec
{ 0xeeee, -5 }, // ????
};
static vidpid_score_t vidpid_score[] = {
{ 0x03f0, 0xbd07, 10 }, // HP Desktop HD BD07
{ 0x0402, 0x5621, 10 }, // ALi M5621
// NOT in VID list as 040d:6205 is a card reader
{ 0x040d, 0x6204, 10 }, // Connectland BE-USB2-35BP-LCM
// NOT in VID list as 043e:70e2 & 043e:70d3 are flash drives
{ 0x043e, 0x70f1, 10 }, // LG Mini HXD5
// NOT in VID list as 0471:0855 is a flash drive
{ 0x0471, 0x2021, 10 }, // Philips
// NOT in VID list as many UFDs and card readers exist
{ 0x05e3, 0x0718, 10 }, // Genesys Logic IDE/SATA Adapter
{ 0x05e3, 0x0719, 10 }, // Genesys Logic SATA adapter
{ 0x05e3, 0x0731, 10 }, // Genesys Logic GL3310 SATA 3Gb/s Bridge Controller
{ 0x05e3, 0x0731, 2 }, // Genesys Logic Mass Storage Device
// Only one HDD device => keep in this list
{ 0x0634, 0x0655, 5 }, // Micron USB SSD
// NOT in VID list as plenty of UFDs
{ 0x0718, 0x1000, 7 }, // Imation Odyssey external USB dock
// Only one HDD device
{ 0x0939, 0x0b16, 10 }, // Toshiba Stor.E
// Plenty of card readers
{ 0x0c0b, 0xb001, 10 }, // Dura Micro
{ 0x0c0b, 0xb159, 10 }, // Dura Micro 509
// Meh
{ 0x0e21, 0x0510, 5 }, // Cowon iAudio X5
{ 0x11b0, 0x6298, 10 }, // Enclosure from Kingston SSDNow notebook upgrade kit
// NOT in VID list as plenty of UFDs
{ 0x125f, 0xa93a, 10 }, // A-DATA SH93
{ 0x125f, 0xa94a, 10 }, // A-DATA DashDrive
// NOT in VID list as plenty of card readers
{ 0x14cd, 0x6116, 10 }, // Super Top generic enclosure
// Verbatim are way too widespread - good candidate for ATA passthrough
{ 0x18a5, 0x0214, 10 }, // Verbatim Portable Hard Drive
{ 0x18a5, 0x0215, 10 }, // Verbatim FW/USB160
{ 0x18a5, 0x0216, 10 }, // Verbatim External Hard Drive 47519
{ 0x18a5, 0x0227, 10 }, // Verbatim Pocket Hard Drive
{ 0x18a5, 0x022a, 10 }, // Verbatim External Hard Drive
{ 0x18a5, 0x022b, 10 }, // Verbatim Portable Hard Drive (Store'n'Go)
{ 0x18a5, 0x0237, 10 }, // Verbatim Portable Hard Drive (500 GB)
// SunPlus seem to have a bunch of UFDs
{ 0x1bcf, 0x0c31, 10 }, // SunplusIT
// Plenty of Innostor UFDs
{ 0x1f75, 0x0888, 10 }, // Innostor IS888
// NOT in VID list as plenty of UFDs
{ 0x3538, 0x0902, 10 }, // PQI H560
// Too many card readers to be in VID list
{ 0x55aa, 0x0015, 10 }, // OnSpec Hard Drive
{ 0x55aa, 0x0102, 8 }, // OnSpec SuperDisk
{ 0x55aa, 0x0103, 10 }, // OnSpec IDE Hard Drive
{ 0x55aa, 0x1234, 8 }, // OnSpec ATAPI Bridge
{ 0x55aa, 0x2b00, 8 }, // OnSpec USB->PATA
// Smartmontools are uncertain about that one, and so am I
{ 0x6795, 0x2756, 2 }, // Sharkoon 2-Bay RAID Box
// OCZ exceptions
{ 0x0324, 0xbc06, -20 }, // OCZ ATV USB 2.0 Flash Drive
{ 0x0324, 0xbc08, -20 }, // OCZ Rally2 / ATV USB 2.0 Flash Drive
{ 0x0325, 0xac02, -20 }, // OCZ ATV Turbo / Rally2 Dual Channel USB 2.0 Flash Drive
// Buffalo exceptions
{ 0x0411, 0x01e8, -20 }, // Buffalo HD-PNTU2
// Samsung exceptions
{ 0x04e8, 0x0100, -20 }, // Kingston Flash Drive (128MB)
{ 0x04e8, 0x0100, -20 }, // Connect3D Flash Drive
{ 0x04e8, 0x0101, -20 }, // Connect3D Flash Drive
{ 0x04e8, 0x1a23, -20 }, // 2 GB UFD
{ 0x04e8, 0x5120, -20 }, // 4 GB UFD
{ 0x04e8, 0x6818, -20 }, // 8 GB UFD
{ 0x04e8, 0x6845, -20 }, // 16 GB UFD
{ 0x04e8, 0x685E, -20 }, // 16 GB UFD
// Sunplus exceptions
{ 0x04fc, 0x05d8, -20 }, // Verbatim Flash Drive
{ 0x04fc, 0x5720, -20 }, // Card Reader
// LaCie exceptions
{ 0x059f, 0x1027, -20 }, // 16 GB UFD
{ 0x059f, 0x103B, -20 }, // 16 GB UFD
{ 0x059f, 0x1064, -20 }, // 16 GB UFD
{ 0x059f, 0x1079, -20 }, // LaCie XtremKey UFD
// Apple exceptions
{ 0x05ac, 0x8400, -20},
{ 0x05ac, 0x8401, -20},
{ 0x05ac, 0x8402, -20},
{ 0x05ac, 0x8403, -20},
{ 0x05ac, 0x8404, -20},
{ 0x05ac, 0x8405, -20},
{ 0x05ac, 0x8406, -20},
{ 0x05ac, 0x8407, -20},
// Prolific exceptions
{ 0x067b, 0x2506, -20 }, // 8 GB Micro Hard Drive
{ 0x067b, 0x2517, -20 }, // 1 GB UFD
{ 0x067b, 0x2528, -20 }, // 8 GB UFD
{ 0x067b, 0x2731, -20 }, // SD/TF Card Reader
{ 0x067b, 0x2733, -20 }, // EAGET Mass Storage USB Device
{ 0x067b, 0x3400, -10 }, // Hi-Speed Flash Disk with TruePrint AES3400
{ 0x067b, 0x3500, -10 }, // Hi-Speed Flash Disk with TruePrint AES3500
// Sandisk exceptions
{ 0x0781, 0x5580, -20 },
// Freecom exceptions
{ 0x07ab, 0xfcab, -20 }, // 4 GB UFD
// Samsung exceptions
{ 0x090c, 0x1000, -20 }, // Samsung Flash Drive
// Toshiba exceptions
{ 0x0930, 0x1400, -20 },
{ 0x0930, 0x6533, -20 },
{ 0x0930, 0x653e, -20 },
{ 0x0930, 0x6544, -20 },
{ 0x0930, 0x6545, -20 },
// Innostor exceptions
{ 0x0bc2, 0x3312, -20 },
// JMicron exceptions
{ 0x152d, 0x0901, -20 },
// Verbatim exceptions
{ 0x18a5, 0x0243, -20 },
{ 0x18a5, 0x0245, -20 },
{ 0x18a5, 0x0302, -20 },
{ 0x18a5, 0x0304, -20 },
{ 0x18a5, 0x3327, -20 },
// More Innostor
{ 0x1f75, 0x0917, -10 }, // Intenso Speed Line USB Device
// ??? (https://github.com/pbatard/rufus/issues/2247)
{ 0x23a9, 0xef18, -10 },
// No idea who these guys are. They don't exist in usb.ids.
{ 0x6557, 0x0021, -5 },
};
| 10,719 |
C
|
.h
| 300 | 33.756667 | 106 | 0.632747 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
4,876 |
winio.h
|
pbatard_rufus/src/winio.h
|
/*
* Rufus: The Reliable USB Formatting Utility
* Windows I/O redefinitions, that would be totally unnecessary had
* Microsoft done a proper job with their asynchronous APIs.
* Copyright © 2021-2024 Pete Batard <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <windows.h>
#include "msapi_utf8.h"
#pragma once
// https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-overlapped
// See Microsoft? It's not THAT hard to define an OVERLAPPED struct in a manner that
// doesn't qualify as an example of "Crimes against humanity" in the Geneva convention.
typedef struct {
ULONG_PTR Internal[2];
ULONG64 Offset;
HANDLE hEvent;
BOOL bOffsetUpdated;
} NOW_THATS_WHAT_I_CALL_AN_OVERLAPPED;
// File Descriptor for asynchronous accesses.
// The status field is a threestate value reflecting the result
// of the current asynchronous read operation:
// 1: Read was successful and completed synchronously
// -1: Read is pending asynchronously
// 0: Read Error
typedef struct {
HANDLE hFile;
INT iStatus;
NOW_THATS_WHAT_I_CALL_AN_OVERLAPPED Overlapped;
} ASYNC_FD;
/// <summary>
/// Open a file for asynchronous access. The values for the flags are the same as the ones
/// for the native CreateFile() call. Note that FILE_FLAG_OVERLAPPED will always be added
/// to dwFlagsAndAttributes before the file is instantiated, and that an internal
/// OVERLAPPED structure with its associated wait event is also created.
/// </summary>
/// <param name="lpFileName">The name of the file or device to be created or opened</param>
/// <param name="dwDesiredAccess">The requested access to the file or device</param>
/// <param name="dwShareMode">The requested sharing mode of the file or device</param>
/// <param name="dwCreationDisposition">Action to take on a file or device that exists or does not exist</param>
/// <param name="dwFlagsAndAttributes">The file or device attributes and flags</param>
/// <returns>Non NULL on success</returns>
static __inline HANDLE CreateFileAsync(LPCSTR lpFileName, DWORD dwDesiredAccess,
DWORD dwShareMode, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes)
{
ASYNC_FD* fd = calloc(sizeof(ASYNC_FD), 1);
if (fd == NULL) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return NULL;
}
fd->Overlapped.hEvent = CreateEventA(NULL, TRUE, FALSE, NULL);
fd->hFile = CreateFileU(lpFileName, dwDesiredAccess, dwShareMode, NULL,
dwCreationDisposition, FILE_FLAG_OVERLAPPED | dwFlagsAndAttributes, NULL);
if (fd->hFile == INVALID_HANDLE_VALUE) {
CloseHandle(fd->Overlapped.hEvent);
free(fd);
return NULL;
}
return fd;
}
/// <summary>
/// Close a previously opened asynchronous file
/// </summary>
/// <param name="h">An async handle, created by a call to CreateFileAsync()</param>
static __inline VOID CloseFileAsync(HANDLE h)
{
ASYNC_FD* fd = (ASYNC_FD*)h;
if (fd == NULL || fd == INVALID_HANDLE_VALUE)
return;
CloseHandle(fd->hFile);
CloseHandle(fd->Overlapped.hEvent);
free(fd);
}
/// <summary>
/// Initiate a read operation for asynchronous I/O.
/// </summary>
/// <param name="h">An async handle, created by a call to CreateFileAsync()</param>
/// <param name="lpBuffer">The buffer that receives the data</param>
/// <param name="nNumberOfBytesToRead">Number of bytes requested</param>
/// <returns>TRUE on success, FALSE on error</returns>
static __inline BOOL ReadFileAsync(HANDLE h, LPVOID lpBuffer, DWORD nNumberOfBytesToRead)
{
ASYNC_FD* fd = (ASYNC_FD*)h;
fd->Overlapped.bOffsetUpdated = FALSE;
if (!ReadFile(fd->hFile, lpBuffer, nNumberOfBytesToRead, NULL,
(OVERLAPPED*)&fd->Overlapped)) {
// Is it possible to get ERROR_HANDLE_EOF here?
assert(GetLastError() != ERROR_HANDLE_EOF);
fd->iStatus = (GetLastError() == ERROR_IO_PENDING) ? -1 : 0;
} else {
fd->iStatus = 1;
}
return (fd->iStatus != 0);
}
/// <summary>
/// Initiate a write operation for asynchronous I/O.
/// </summary>
/// <param name="h">An async handle, created by a call to CreateFileAsync()</param>
/// <param name="lpBuffer">The buffer that contains the data</param>
/// <param name="nNumberOfBytesToWrite">Number of bytes to write</param>
/// <returns>TRUE on success, FALSE on error</returns>
static __inline BOOL WriteFileAsync(HANDLE h, LPVOID lpBuffer, DWORD nNumberOfBytesToWrite)
{
ASYNC_FD* fd = (ASYNC_FD*)h;
fd->Overlapped.bOffsetUpdated = FALSE;
if (!WriteFile(fd->hFile, lpBuffer, nNumberOfBytesToWrite, NULL,
(OVERLAPPED*)&fd->Overlapped))
// TODO: Is it possible to get ERROR_HANDLE_EOF here?
fd->iStatus = (GetLastError() == ERROR_IO_PENDING) ? -1 : 0;
else
fd->iStatus = 1;
return (fd->iStatus != 0);
}
/// <summary>
/// Wait for an asynchronous operation to complete, with timeout.
/// This function also succeeds if the I/O already completed synchronously.
/// </summary>
/// <param name="h">An async handle, created by a call to CreateFileAsync()</param>
/// <param name="dwTimeout">A timeout value, in ms</param>
/// <returns>TRUE on success, FALSE on error</returns>
static __inline BOOL WaitFileAsync(HANDLE h, DWORD dwTimeout)
{
ASYNC_FD* fd = (ASYNC_FD*)h;
if (fd->iStatus > 0) // Read completed synchronously
return TRUE;
return (WaitForSingleObject(fd->Overlapped.hEvent, dwTimeout) == WAIT_OBJECT_0);
}
/// <summary>
/// Return the number of bytes read or written and keep track/update the
/// current offset for an asynchronous read operation.
/// </summary>
/// <param name="h">An async handle, created by a call to CreateFileAsync()</param>
/// <param name="lpNumberOfBytes">A pointer that receives the number of bytes transferred.</param>
/// <returns>TRUE on success, FALSE on error</returns>
static __inline BOOL GetSizeAsync(HANDLE h, LPDWORD lpNumberOfBytes)
{
ASYNC_FD* fd = (ASYNC_FD*)h;
// Previous call to [Read/Write]FileAsync() failed
if (fd->iStatus == 0) {
*lpNumberOfBytes = 0;
return FALSE;
}
// Detect if we already read the size and updated the offset
if (fd->Overlapped.bOffsetUpdated) {
SetLastError(ERROR_NO_MORE_ITEMS);
return FALSE;
}
fd->Overlapped.bOffsetUpdated = TRUE;
if (!GetOverlappedResultEx(fd->hFile, (OVERLAPPED*)&fd->Overlapped,
lpNumberOfBytes, WRITE_TIMEOUT, (fd->iStatus < 0)))
// When reading from VHD/VHDX we get SECTOR_NOT_FOUND rather than EOF for the end of the drive
return (GetLastError() == ERROR_HANDLE_EOF || GetLastError() == ERROR_SECTOR_NOT_FOUND);
fd->Overlapped.Offset += *lpNumberOfBytes;
return TRUE;
}
| 7,188 |
C
|
.h
| 167 | 41.419162 | 112 | 0.727999 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
4,879 |
cpu.h
|
pbatard_rufus/src/cpu.h
|
/*
* Rufus: The Reliable USB Formatting Utility
* CPU features detection
* Copyright © 2022 Pete Batard <[email protected]>
* Copyright © 2022 Jeffrey Walton <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Primarily added to support SHA instructions on x86 machines.
* SHA acceleration is becoming as ubiquitous as AES acceleration.
* SHA support was introduced in Intel Goldmont architecture, like
* Celeron J3455 and Pentium J4205. The instructions are now present
* in AMD Ryzen 3 (Zen architecture) and above, and Intel Core
* 10th-gen processors (Ice Lake), 11th-gen processors (Rocket Lake)
* and above.
*
* Typical benchmarks for x86 SHA acceleration is about a 6x to 10x
* speedup over a C/C++ implementation. The rough measurements are
* 1.0 to 1.8 cpb for SHA-1, and 1.5 to 2.5 cpb for SHA-256. On a
* Celeron J3455, that's 1.1 GB/s for SHA-1 and 800 MB/s for SHA-256.
* On a 10th-gen Core i5, that's about 1.65 GB/s for SHA-1 and about
* 1.3 GB/s for SHA-256.
*/
#include "rufus.h"
#pragma once
#ifdef _MSC_VER
#define RUFUS_MSC_VERSION (_MSC_VER)
#if (RUFUS_MSC_VERSION < 1900)
#error "Your compiler is too old to build this application"
#endif
#endif
#if defined(__GNUC__)
#define RUFUS_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#if (RUFUS_GCC_VERSION < 40900)
#error "Your compiler is too old to build this application"
#endif
#endif
#ifdef __INTEL_COMPILER
#define RUFUS_INTEL_VERSION (__INTEL_COMPILER)
#if (RUFUS_INTEL_VERSION < 1600)
#error "Your compiler is too old to build this application"
#endif
#endif
#if defined(__clang__)
#define RUFUS_CLANG_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__)
#if (RUFUS_CLANG_VERSION < 30400)
#error "Your compiler is too old to build this application"
#endif
#endif
#if (defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || \
defined(_X86_) || defined(__I86__) || defined(__x86_64__))
#define CPU_X86_SHA1_ACCELERATION 1
#define CPU_X86_SHA256_ACCELERATION 1
#endif
extern BOOL cpu_has_sha1_accel, cpu_has_sha256_accel;
extern BOOL DetectSHA1Acceleration(void);
extern BOOL DetectSHA256Acceleration(void);
| 2,820 |
C
|
.h
| 69 | 39.144928 | 100 | 0.741146 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
4,883 |
config.h
|
pbatard_rufus/src/libcdio/config.h
|
/* config.h for libcdio (used by both MinGW and MSVC) */
#if defined(_MSC_VER)
/* Disable: warning C4996: The POSIX name for this item is deprecated. */
#pragma warning(disable:4996)
/* Disable: warning C4018: signed/unsigned mismatch */
#pragma warning(disable:4018)
/* Disable: warning C4242: conversion from 'x' to 'y', possible loss of data */
#pragma warning(disable:4242) /* 32 bit */
#pragma warning(disable:4244) /* 64 bit */
#pragma warning(disable:4267) /* 64 bit */
#endif
/* what to put between the brackets for empty arrays */
#define EMPTY_ARRAY_SIZE
/* Define to 1 if you have the `chdir' function. */
/* #undef HAVE_CHDIR */
/* Define if time.h defines extern long timezone and int daylight vars. */
#define HAVE_DAYLIGHT 1
/* Define to 1 if you have the `drand48' function. */
/* #undef HAVE_DRAND48 */
/* Define to 1 if you have the <errno.h> header file. */
#define HAVE_ERRNO_H 1
/* Define to 1 if you have the <fcntl.h> header file. */
#define HAVE_FCNTL_H 1
/* Define to 1 if you have the `lseek64' function. */
#define HAVE_LSEEK64 1
/* The equivalent of lseek64 on MSVC is _lseeki64 */
#define lseek64 _lseeki64
/* Define to 1 if you have the `fseeko' function. */
/* #undef HAVE_FSEEKO */
/* Define to 1 if you have the `fseeko64' function. */
#define HAVE_FSEEKO64 1
#if defined(_MSC_VER)
/* The equivalent of fseeko64 for MSVC is _fseeki64 */
#define fseeko64 _fseeki64
#endif
/* Define to 1 if you have the `ftruncate' function. */
/* #undef HAVE_FTRUNCATE */
/* Define if you have the iconv() function and it works. */
/* #undef HAVE_ICONV */
/* Define this if you want to use the 2020 version of the libcdio API. */
#define DO_NOT_WANT_COMPATIBILITY /**/
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1 /* provided in MSVC/missing if needed */
/* Supports ISO _Pragma() macro */
/* #undef HAVE_ISOC99_PRAGMA */
/* Define 1 if you want ISO-9660 Joliet extension support. You must have also
libiconv installed to get Joliet extension support. */
#define HAVE_JOLIET 1
/* Define to 1 if you have the <limits.h> header file. */
#define HAVE_LIMITS_H 1
/* Define to 1 if you have the `lstat' function. */
/* #undef HAVE_LSTAT */
/* Define to 1 if you have the `memcpy' function. */
#define HAVE_MEMCPY 1
/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1
/* Define to 1 if you have the `memset' function. */
#define HAVE_MEMSET 1
/* Define to 1 if you have the `rand' function. */
#define HAVE_RAND 1
/* Define to 1 if you have the `readlink' function. */
/* #undef HAVE_READLINK */
/* Define to 1 if you have the `realpath' function. */
/* #undef HAVE_REALPATH */
/* Define 1 if you want ISO-9660 Rock-Ridge extension support. */
#define HAVE_ROCK 1
/* Define to 1 if you have the `setegid' function. */
/* #undef HAVE_SETEGID */
/* Define to 1 if you have the `setenv' function. */
/* #undef HAVE_SETENV */
/* Define to 1 if you have the `seteuid' function. */
/* #undef HAVE_SETEUID */
/* Define to 1 if you have the `sleep' function. */
/* #undef HAVE_SLEEP */
/* Define to 1 if you have the `snprintf' function. */
#if defined(_MSC_VER) && (_MSC_VER >= 1900)
#define HAVE_SNPRINTF 1
#endif
/* Define to 1 if you have the `vsnprintf' function. */
#if defined(_MSC_VER) && (_MSC_VER >= 1900)
#define HAVE_VSNPRINTF
#endif
/* Define to 1 if you have the <stdarg.h> header file. */
#define HAVE_STDARG_H 1
/* Define to 1 if you have the <stdbool.h> header file. */
/* #undef HAVE_STDBOOL_H */
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1 /* provided in MSVC/missing if needed */
/* Define to 1 if you have the <stdio.h> header file. */
#define HAVE_STDIO_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the `strdup' function. */
#define HAVE_STRDUP 1
/* The equivalent of strdup on MSVC is _strdup */
#define strdup _strdup
/* Define to 1 if you have the <strings.h> header file. */
/* #undef HAVE_STRINGS_H */
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the `strndup' function. */
#if defined(__MINGW32__)
#define HAVE_STRNDUP 1
#endif
/* Define this if you have struct timespec */
/* #undef HAVE_STRUCT_TIMESPEC */
/* Define to 1 if you have the <sys/cdio.h> header file. */
/* #undef HAVE_SYS_CDIO_H */
/* Define to 1 if you have the <sys/param.h> header file. */
/* #undef HAVE_SYS_PARAM_H */
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/time.h> header file. */
#define HAVE_SYS_TIME_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define this <sys/stat.h> defines S_ISLNK() */
/* #undef HAVE_S_ISLNK */
/* Define this <sys/stat.h> defines S_ISSOCK() */
/* #undef HAVE_S_ISSOCK */
/* Define if you have an extern long timenzone variable. */
#define HAVE_TIMEZONE_VAR 1
/* Define if struct tm has the tm_gmtoff member. */
/* #undef HAVE_TM_GMTOFF */
/* Define if time.h defines extern extern char *tzname[2] variable */
#define HAVE_TZNAME 1
/* The equivalent of tzset on MSVC is _tzset */
#define tzset _tzset
/* Define to 1 if you have the `tzset' function. */
#define HAVE_TZSET 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1 /* provided in MSVC/missing if needed */
/* Define to 1 if you have the `unsetenv' function. */
/* #undef HAVE_UNSETENV */
/* Define to 1 if you have the `usleep' function. */
/* #undef HAVE_USLEEP */
/* Define to 1 if you have the `vsnprintf' function. */
/* #undef HAVE_VSNPRINTF */
/* Define 1 if you have MinGW CD-ROM support */
/* #undef HAVE_WIN32_CDROM */
/* Define to 1 if you have the <windows.h> header file. */
#define HAVE_WINDOWS_H 1
/* Define to 1 if you have the `_stati64' function. */
#define HAVE__STATI64 1
/* Define as const if the declaration of iconv() needs const. */
/* #undef ICONV_CONST */
/* Is set when libcdio's config.h has been included. Applications wishing to
sue their own config.h values (such as set by the application's configure
script can define this before including any of libcdio's headers. */
#define LIBCDIO_CONFIG_H 1
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Number of bits in a file offset, on hosts where this is settable. */
/* Note: This is defined as a preprocessor macro in the project files */
#define _FILE_OFFSET_BITS 64
/* Define to `__inline__' or `__inline' if that's what the C compiler
calls it, or to nothing if 'inline' is not supported under any name. */
#define inline __inline
| 6,938 |
C
|
.h
| 158 | 41.012658 | 80 | 0.688421 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
4,921 |
sltypes.h
|
pbatard_rufus/src/syslinux/sltypes.h
|
#ifndef _MSC_VER
#error This header should only be used with Microsoft compilers
#endif
/* The addons below are not part of inttypes but required for syslinux */
#ifndef _SLTYPES_H_
#define _SLTYPES_H_
/* On MS environments, the inline keyword is available in C++ only */
#ifndef inline
#define inline __inline
#endif
/* ssize_t is also not available (copy/paste from MinGW) */
#ifndef _SSIZE_T_DEFINED
#define _SSIZE_T_DEFINED
#undef ssize_t
#ifdef _WIN64
typedef __int64 ssize_t;
#else
typedef int ssize_t;
#endif /* _WIN64 */
#endif /* _SSIZE_T_DEFINED */
#endif
| 574 |
C
|
.h
| 21 | 25.952381 | 73 | 0.748634 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,922 |
libfat.h
|
pbatard_rufus/src/syslinux/libfat/libfat.h
|
/* ----------------------------------------------------------------------- *
*
* Copyright 2004-2008 H. Peter Anvin - All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, Inc., 53 Temple Place Ste 330,
* Boston MA 02111-1307, USA; either version 2 of the License, or
* (at your option) any later version; incorporated herein by reference.
*
* ----------------------------------------------------------------------- */
/*
* libfat.h
*
* Headers for the libfat library
*/
#ifndef LIBFAT_H
#define LIBFAT_H
#include <stddef.h>
#include <inttypes.h>
// Workaround for 4K support
extern uint32_t LIBFAT_SECTOR_SHIFT;
extern uint32_t LIBFAT_SECTOR_SIZE;
extern uint32_t LIBFAT_SECTOR_MASK;
//#define LIBFAT_SECTOR_SHIFT 9
//#define LIBFAT_SECTOR_SIZE 512
//#define LIBFAT_SECTOR_MASK 511
typedef uint64_t libfat_sector_t;
struct libfat_filesystem;
struct libfat_direntry {
libfat_sector_t sector;
int offset;
unsigned char entry[32];
};
typedef struct libfat_dirpos {
int32_t cluster;
int32_t offset;
libfat_sector_t sector;
} libfat_dirpos_t;
typedef struct libfat_diritem {
wchar_t name[256];
uint32_t size;
uint8_t attributes; /* [--ad-shr] */
} libfat_diritem_t;
/*
* Open the filesystem. The readfunc is the function to read
* sectors, in the format:
* int readfunc(intptr_t readptr, void *buf, size_t secsize,
* libfat_sector_t secno)
*
* ... where readptr is a private argument.
*
* A return value of != secsize is treated as error.
*/
struct libfat_filesystem
*libfat_open(int (*readfunc) (intptr_t, void *, size_t, libfat_sector_t),
intptr_t readptr);
void libfat_close(struct libfat_filesystem *);
/*
* Convert a cluster number (or 0 for the root directory) to a
* sector number. Return -1 on failure.
*/
libfat_sector_t libfat_clustertosector(const struct libfat_filesystem *fs,
int32_t cluster);
/*
* Get the next sector of either the root directory or a FAT chain.
* Returns 0 on end of file and -1 on error.
*/
libfat_sector_t libfat_nextsector(struct libfat_filesystem *fs,
libfat_sector_t s);
/*
* Flush all cached sectors for this filesystem.
*/
void libfat_flush(struct libfat_filesystem *fs);
/*
* Get a pointer to a specific sector.
*/
void *libfat_get_sector(struct libfat_filesystem *fs, libfat_sector_t n);
/*
* Search a FAT directory for a particular pre-mangled filename.
* Copies the directory entry into direntry and returns 0 if found.
*/
int32_t libfat_searchdir(struct libfat_filesystem *fs, int32_t dirclust,
const void *name, struct libfat_direntry *direntry);
/*
* Return all the files and directory items from a FAT directory.
* Initial call must set dp->offset to negative and dp->cluster to the cluster
* that contains the directory data. After that each subsequent call must use
* the same dp.
* Return value is the cluster for the corresponding item or negative on error.
*/
int libfat_dumpdir(struct libfat_filesystem *fs, libfat_dirpos_t *dp,
libfat_diritem_t *di);
#endif /* LIBFAT_H */
| 3,225 |
C
|
.h
| 94 | 31.946809 | 79 | 0.697816 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,929 |
syslinux.h
|
pbatard_rufus/src/syslinux/libinstaller/syslinux.h
|
/* ----------------------------------------------------------------------- *
*
* Copyright 1998-2008 H. Peter Anvin - All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, Inc., 53 Temple Place Ste 330,
* Boston MA 02111-1307, USA; either version 2 of the License, or
* (at your option) any later version; incorporated herein by reference.
*
* ----------------------------------------------------------------------- */
#ifndef SYSLINUX_H
#define SYSLINUX_H
#include <inttypes.h>
#include "advconst.h"
#include "setadv.h"
#ifdef __CHECKER__
# define _slimg __attribute__((noderef,address_space(1)))
# define _force __attribute__((force))
#else
# define _slimg
# define _force
#endif
/* The standard boot sector and ldlinux image */
extern unsigned char* syslinux_ldlinux[2];
extern unsigned long syslinux_ldlinux_len[2];
extern const int syslinux_ldlinux_mtime[2];
#define boot_sector syslinux_ldlinux[1]
#define boot_sector_len syslinux_ldlinux_len[1]
#define boot_image syslinux_ldlinux[0]
#define boot_image_len syslinux_ldlinux_len[0]
extern unsigned char syslinux_mbr[];
extern const unsigned int syslinux_mbr_len;
extern const int syslinux_mbr_mtime;
/* Sector size variables are defined externally for 4K support */
extern uint32_t SECTOR_SHIFT;
extern uint32_t SECTOR_SIZE;
/* This takes a boot sector and merges in the syslinux fields */
void syslinux_make_bootsect(void *bs, int fs_type);
/* Check to see that what we got was indeed an MS-DOS boot sector/superblock */
const char *syslinux_check_bootsect(const void *bs, int *fs_type);
/* This patches the boot sector and ldlinux.sys based on a sector map */
typedef uint64_t sector_t;
int syslinux_patch(const sector_t *sectors, int nsectors,
int stupid, int raid_mode,
const char *subdir, const char *subvol);
#endif
| 1,963 |
C
|
.h
| 47 | 40.106383 | 79 | 0.701837 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,932 |
syslxfs.h
|
pbatard_rufus/src/syslinux/libinstaller/syslxfs.h
|
/*
* Copyright 2011-2012 Paulo Alcantara <[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, Inc., 53 Temple Place Ste 330,
* Boston MA 02111-1307, USA; either version 2 of the License, or
* (at your option) any later version; incorporated herein by reference.
*
* ----------------------------------------------------------------------- */
#ifndef _SYSLXFS_H_
#define _SYSLXFS_H_
/* Global fs_type for handling fat, ntfs, ext2/3/4, btrfs, xfs and ufs1/2 */
enum filesystem {
NONE,
EXT2,
BTRFS,
VFAT,
NTFS,
XFS,
UFS1,
UFS2,
};
//extern int fs_type;
#endif /* _SYSLXFS_H_ */
| 797 |
C
|
.h
| 25 | 28.12 | 78 | 0.604712 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,962 |
ntfs.h
|
pbatard_rufus/src/ms-sys/inc/ntfs.h
|
#ifndef NTFS_H
#define NTFS_H
#include <stdio.h>
/* returns TRUE if the file has an NFTS file system, otherwise FALSE.
The file position will change when this function is called! */
int is_ntfs_fs(FILE *fp);
/* returns TRUE if the file has a NTFS boot record, otherwise FALSE.
The file position will change when this function is called! */
int is_ntfs_br(FILE *fp);
/* returns TRUE if the file has an exact match of the NTFS boot record
this program would create, otherwise FALSE.
The file position will change when this function is called! */
int entire_ntfs_br_matches(FILE *fp);
/* Writes a NTFS boot record to a file, returns TRUE on success, otherwise
FALSE */
int write_ntfs_br(FILE *fp);
#endif
| 723 |
C
|
.h
| 17 | 40.294118 | 74 | 0.751429 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,963 |
libintl.h
|
pbatard_rufus/src/ms-sys/inc/libintl.h
|
#ifndef LIBINTL_H
#define LIBINTL_H
/* This file is only supposed to be used on systems which doesn't have a
builtin libintl.h and which also miss gnu gettext */
#define NO_LIBINTL_OR_GETTEXT
#endif
| 205 |
C
|
.h
| 6 | 32.166667 | 72 | 0.780612 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,964 |
br_fat32fd_0x52.h
|
pbatard_rufus/src/ms-sys/inc/br_fat32fd_0x52.h
|
/* br_fat32_0x52.h
//
// ANI
// substring gmbh/tw 14.9.04
// modified bootstrap code 0x052 to support FreeDOS
*/
unsigned char br_fat32_0x52[] = {
0x46, 0x41, 0x54, 0x33, 0x32, 0x20, 0x20, 0x20, 0xfc, 0xfa, 0x29, 0xc0,
0x8e, 0xd8, 0xbd, 0x00, 0x7c, 0xb8, 0xe0, 0x1f, 0x8e, 0xc0, 0x89, 0xee,
0x89, 0xef, 0xb9, 0x00, 0x01, 0xf3, 0xa5, 0xea, 0x7a, 0x7c, 0xe0, 0x1f,
0x00, 0x00, 0x60, 0x00, 0x8e, 0xd8, 0x8e, 0xd0, 0x8d, 0x66, 0xe0, 0xfb,
0x88, 0x56, 0x40, 0xbe, 0xc1, 0x7d, 0xe8, 0xf4, 0x00, 0x66, 0x31, 0xc0,
0x66, 0x89, 0x46, 0x44, 0x8b, 0x46, 0x0e, 0x66, 0x03, 0x46, 0x1c, 0x66,
0x89, 0x46, 0x48, 0x66, 0x89, 0x46, 0x4c, 0x66, 0x8b, 0x46, 0x10, 0x66,
0xf7, 0x6e, 0x24, 0x66, 0x01, 0x46, 0x4c, 0xb8, 0x00, 0x02, 0x3b, 0x46,
0x0b, 0x74, 0x08, 0x01, 0xc0, 0xff, 0x06, 0x34, 0x7d, 0xeb, 0xf3, 0x66,
0x8b, 0x46, 0x2c, 0x66, 0x50, 0xe8, 0x94, 0x00, 0x72, 0x4d, 0xc4, 0x5e,
0x76, 0xe8, 0xb7, 0x00, 0x31, 0xff, 0xb9, 0x0b, 0x00, 0xbe, 0xf1, 0x7d,
0xf3, 0xa6, 0x74, 0x15, 0x83, 0xc7, 0x20, 0x83, 0xe7, 0xe0, 0x3b, 0x7e,
0x0b, 0x75, 0xeb, 0x4a, 0x75, 0xe0, 0x66, 0x58, 0xe8, 0x34, 0x00, 0xeb,
0xd2, 0x26, 0xff, 0x75, 0x09, 0x26, 0xff, 0x75, 0x0f, 0x66, 0x58, 0x29,
0xdb, 0x66, 0x50, 0xe8, 0x5a, 0x00, 0x72, 0x0d, 0xe8, 0x80, 0x00, 0x4a,
0x75, 0xfa, 0x66, 0x58, 0xe8, 0x14, 0x00, 0xeb, 0xec, 0x8a, 0x5e, 0x40,
0xff, 0x6e, 0x76, 0xbe, 0xee, 0x7d, 0xe8, 0x64, 0x00, 0x30, 0xe4, 0xcd,
0x16, 0xcd, 0x19, 0x06, 0x57, 0x53, 0x89, 0xc7, 0xc1, 0xe7, 0x02, 0x50,
0x8b, 0x46, 0x0b, 0x48, 0x21, 0xc7, 0x58, 0x66, 0xc1, 0xe8, 0x07, 0x66,
0x03, 0x46, 0x48, 0xbb, 0x00, 0x20, 0x8e, 0xc3, 0x29, 0xdb, 0x66, 0x3b,
0x46, 0x44, 0x74, 0x07, 0x66, 0x89, 0x46, 0x44, 0xe8, 0x38, 0x00, 0x26,
0x80, 0x65, 0x03, 0x0f, 0x26, 0x66, 0x8b, 0x05, 0x5b, 0x5f, 0x07, 0xc3,
0x66, 0x3d, 0xf8, 0xff, 0xff, 0x0f, 0x73, 0x15, 0x66, 0x48, 0x66, 0x48,
0x66, 0x0f, 0xb6, 0x56, 0x0d, 0x66, 0x52, 0x66, 0xf7, 0xe2, 0x66, 0x5a,
0x66, 0x03, 0x46, 0x4c, 0xc3, 0xf9, 0xc3, 0x31, 0xdb, 0xb4, 0x0e, 0xcd,
0x10, 0xac, 0x3c, 0x00, 0x75, 0xf5, 0xc3, 0x52, 0x56, 0x57, 0x66, 0x50,
0x89, 0xe7, 0x6a, 0x00, 0x6a, 0x00, 0x66, 0x50, 0x06, 0x53, 0x6a, 0x01,
0x6a, 0x10, 0x89, 0xe6, 0x8a, 0x56, 0x40, 0xb4, 0x42, 0xcd, 0x13, 0x89,
0xfc, 0x66, 0x58, 0x73, 0x08, 0x50, 0x30, 0xe4, 0xcd, 0x13, 0x58, 0xeb,
0xd9, 0x66, 0x40, 0x03, 0x5e, 0x0b, 0x73, 0x07, 0x8c, 0xc2, 0x80, 0xc6,
0x10, 0x8e, 0xc2, 0x5f, 0x5e, 0x5a, 0xc3, 0x4c, 0x6f, 0x61, 0x64, 0x69,
0x6e, 0x67, 0x20, 0x46, 0x72, 0x65, 0x65, 0x44, 0x4f, 0x53, 0x20, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x4e, 0x6f, 0x20, 0x4b, 0x45, 0x52, 0x4e, 0x45,
0x4c, 0x20, 0x20, 0x53, 0x59, 0x53, 0x00, 0x00, 0x55, 0xaa, 0x52, 0x52,
0x61, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x72, 0x72, 0x41, 0x61
};
| 6,043 |
C
|
.h
| 85 | 65.552941 | 76 | 0.633205 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,965 |
mbr_syslinux.h
|
pbatard_rufus/src/ms-sys/inc/mbr_syslinux.h
|
/* This version is from mbr.bin from syslinux 6.02 */
unsigned char mbr_syslinux_0x0[] = {
0x33, 0xc0, 0xfa, 0x8e, 0xd8, 0x8e, 0xd0, 0xbc, 0x00, 0x7c, 0x89, 0xe6,
0x06, 0x57, 0x8e, 0xc0, 0xfb, 0xfc, 0xbf, 0x00, 0x06, 0xb9, 0x00, 0x01,
0xf3, 0xa5, 0xea, 0x1f, 0x06, 0x00, 0x00, 0x52, 0x52, 0xb4, 0x41, 0xbb,
0xaa, 0x55, 0x31, 0xc9, 0x30, 0xf6, 0xf9, 0xcd, 0x13, 0x72, 0x13, 0x81,
0xfb, 0x55, 0xaa, 0x75, 0x0d, 0xd1, 0xe9, 0x73, 0x09, 0x66, 0xc7, 0x06,
0x8d, 0x06, 0xb4, 0x42, 0xeb, 0x15, 0x5a, 0xb4, 0x08, 0xcd, 0x13, 0x83,
0xe1, 0x3f, 0x51, 0x0f, 0xb6, 0xc6, 0x40, 0xf7, 0xe1, 0x52, 0x50, 0x66,
0x31, 0xc0, 0x66, 0x99, 0xe8, 0x66, 0x00, 0xe8, 0x35, 0x01, 0x4d, 0x69,
0x73, 0x73, 0x69, 0x6e, 0x67, 0x20, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74,
0x69, 0x6e, 0x67, 0x20, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x2e, 0x0d,
0x0a, 0x66, 0x60, 0x66, 0x31, 0xd2, 0xbb, 0x00, 0x7c, 0x66, 0x52, 0x66,
0x50, 0x06, 0x53, 0x6a, 0x01, 0x6a, 0x10, 0x89, 0xe6, 0x66, 0xf7, 0x36,
0xf4, 0x7b, 0xc0, 0xe4, 0x06, 0x88, 0xe1, 0x88, 0xc5, 0x92, 0xf6, 0x36,
0xf8, 0x7b, 0x88, 0xc6, 0x08, 0xe1, 0x41, 0xb8, 0x01, 0x02, 0x8a, 0x16,
0xfa, 0x7b, 0xcd, 0x13, 0x8d, 0x64, 0x10, 0x66, 0x61, 0xc3, 0xe8, 0xc4,
0xff, 0xbe, 0xbe, 0x7d, 0xbf, 0xbe, 0x07, 0xb9, 0x20, 0x00, 0xf3, 0xa5,
0xc3, 0x66, 0x60, 0x89, 0xe5, 0xbb, 0xbe, 0x07, 0xb9, 0x04, 0x00, 0x31,
0xc0, 0x53, 0x51, 0xf6, 0x07, 0x80, 0x74, 0x03, 0x40, 0x89, 0xde, 0x83,
0xc3, 0x10, 0xe2, 0xf3, 0x48, 0x74, 0x5b, 0x79, 0x39, 0x59, 0x5b, 0x8a,
0x47, 0x04, 0x3c, 0x0f, 0x74, 0x06, 0x24, 0x7f, 0x3c, 0x05, 0x75, 0x22,
0x66, 0x8b, 0x47, 0x08, 0x66, 0x8b, 0x56, 0x14, 0x66, 0x01, 0xd0, 0x66,
0x21, 0xd2, 0x75, 0x03, 0x66, 0x89, 0xc2, 0xe8, 0xac, 0xff, 0x72, 0x03,
0xe8, 0xb6, 0xff, 0x66, 0x8b, 0x46, 0x1c, 0xe8, 0xa0, 0xff, 0x83, 0xc3,
0x10, 0xe2, 0xcc, 0x66, 0x61, 0xc3, 0xe8, 0x76, 0x00, 0x4d, 0x75, 0x6c,
0x74, 0x69, 0x70, 0x6c, 0x65, 0x20, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65,
0x20, 0x70, 0x61, 0x72, 0x74, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e,
0x0d, 0x0a, 0x66, 0x8b, 0x44, 0x08, 0x66, 0x03, 0x46, 0x1c, 0x66, 0x89,
0x44, 0x08, 0xe8, 0x30, 0xff, 0x72, 0x27, 0x66, 0x81, 0x3e, 0x00, 0x7c,
0x58, 0x46, 0x53, 0x42, 0x75, 0x09, 0x66, 0x83, 0xc0, 0x04, 0xe8, 0x1c,
0xff, 0x72, 0x13, 0x81, 0x3e, 0xfe, 0x7d, 0x55, 0xaa, 0x0f, 0x85, 0xf2,
0xfe, 0xbc, 0xfa, 0x7b, 0x5a, 0x5f, 0x07, 0xfa, 0xff, 0xe4, 0xe8, 0x1e,
0x00, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x73,
0x79, 0x73, 0x74, 0x65, 0x6d, 0x20, 0x6c, 0x6f, 0x61, 0x64, 0x20, 0x65,
0x72, 0x72, 0x6f, 0x72, 0x2e, 0x0d, 0x0a, 0x5e, 0xac, 0xb4, 0x0e, 0x8a,
0x3e, 0x62, 0x04, 0xb3, 0x07, 0xcd, 0x10, 0x3c, 0x0a, 0x75, 0xf1, 0xcd,
0x18, 0xf4, 0xeb, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
| 2,807 |
C
|
.h
| 40 | 67.325 | 73 | 0.659198 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,966 |
br_fat32pe_0x1800.h
|
pbatard_rufus/src/ms-sys/inc/br_fat32pe_0x1800.h
|
unsigned char br_fat32pe_0x1800[] = {
0x66, 0x0f, 0xb6, 0x46, 0x10, 0x66, 0x8b, 0x4e, 0x24, 0x66, 0xf7, 0xe1,
0x66, 0x03, 0x46, 0x1c, 0x66, 0x0f, 0xb7, 0x56, 0x0e, 0x66, 0x03, 0xc2,
0x66, 0x89, 0x46, 0xfc, 0x66, 0xc7, 0x46, 0xf4, 0xff, 0xff, 0xff, 0xff,
0x66, 0x8b, 0x46, 0x2c, 0x66, 0x83, 0xf8, 0x02, 0x0f, 0x82, 0xc2, 0xfc,
0x66, 0x3d, 0xf8, 0xff, 0xff, 0x0f, 0x0f, 0x83, 0xb8, 0xfc, 0x66, 0x50,
0x66, 0x83, 0xe8, 0x02, 0x66, 0x0f, 0xb6, 0x5e, 0x0d, 0x8b, 0xf3, 0x66,
0xf7, 0xe3, 0x66, 0x03, 0x46, 0xfc, 0xbb, 0x00, 0x82, 0x8b, 0xfb, 0xb9,
0x01, 0x00, 0xe8, 0xa3, 0xfc, 0x38, 0x2d, 0x74, 0x1e, 0xb1, 0x0b, 0x56,
0xbe, 0x69, 0x7d, 0xf3, 0xa6, 0x5e, 0x74, 0x1b, 0x03, 0xf9, 0x83, 0xc7,
0x15, 0x3b, 0xfb, 0x72, 0xe8, 0x4e, 0x75, 0xda, 0x66, 0x58, 0xe8, 0x65,
0x00, 0x72, 0xbf, 0x83, 0xc4, 0x04, 0xe9, 0x71, 0xfc, 0x00, 0x20, 0x83,
0xc4, 0x04, 0x8b, 0x75, 0x09, 0x8b, 0x7d, 0x0f, 0x8b, 0xc6, 0x66, 0xc1,
0xe0, 0x10, 0x8b, 0xc7, 0x66, 0x83, 0xf8, 0x02, 0x0f, 0x82, 0x56, 0xfc,
0x66, 0x3d, 0xf8, 0xff, 0xff, 0x0f, 0x0f, 0x83, 0x4c, 0xfc, 0x66, 0x50,
0x66, 0x83, 0xe8, 0x02, 0x66, 0x0f, 0xb6, 0x4e, 0x0d, 0x66, 0xf7, 0xe1,
0x66, 0x03, 0x46, 0xfc, 0xbb, 0x00, 0x00, 0x06, 0x8e, 0x06, 0x81, 0x80,
0xe8, 0x39, 0xfc, 0x07, 0x66, 0x58, 0xc1, 0xeb, 0x04, 0x01, 0x1e, 0x81,
0x80, 0xe8, 0x0e, 0x00, 0x0f, 0x83, 0x02, 0x00, 0x72, 0xd0, 0x8a, 0x56,
0x40, 0xea, 0x00, 0x00, 0x00, 0x20, 0x66, 0xc1, 0xe0, 0x02, 0xe8, 0x11,
0x00, 0x26, 0x66, 0x8b, 0x01, 0x66, 0x25, 0xff, 0xff, 0xff, 0x0f, 0x66,
0x3d, 0xf8, 0xff, 0xff, 0x0f, 0xc3, 0xbf, 0x00, 0x7e, 0x66, 0x0f, 0xb7,
0x4e, 0x0b, 0x66, 0x33, 0xd2, 0x66, 0xf7, 0xf1, 0x66, 0x3b, 0x46, 0xf4,
0x74, 0x3a, 0x66, 0x89, 0x46, 0xf4, 0x66, 0x03, 0x46, 0x1c, 0x66, 0x0f,
0xb7, 0x4e, 0x0e, 0x66, 0x03, 0xc1, 0x66, 0x0f, 0xb7, 0x5e, 0x28, 0x83,
0xe3, 0x0f, 0x74, 0x16, 0x3a, 0x5e, 0x10, 0x0f, 0x83, 0xc7, 0xfb, 0x52,
0x66, 0x8b, 0xc8, 0x66, 0x8b, 0x46, 0x24, 0x66, 0xf7, 0xe3, 0x66, 0x03,
0xc1, 0x5a, 0x52, 0x8b, 0xdf, 0xb9, 0x01, 0x00, 0xe8, 0xb9, 0xfb, 0x5a,
0x8b, 0xda, 0xc3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0xaa
};
| 3,198 |
C
|
.h
| 45 | 68.155556 | 73 | 0.658103 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,967 |
br_fat12_0x3e.h
|
pbatard_rufus/src/ms-sys/inc/br_fat12_0x3e.h
|
unsigned char br_fat12_0x3e[] = {
0x33, 0xc9, 0x8e, 0xd1, 0xbc, 0xfc, 0x7b, 0x16, 0x07, 0xbd,
0x78, 0x00, 0xc5, 0x76, 0x00, 0x1e, 0x56, 0x16, 0x55, 0xbf, 0x22, 0x05,
0x89, 0x7e, 0x00, 0x89, 0x4e, 0x02, 0xb1, 0x0b, 0xfc, 0xf3, 0xa4, 0x06,
0x1f, 0xbd, 0x00, 0x7c, 0xc6, 0x45, 0xfe, 0x0f, 0x38, 0x4e, 0x24, 0x7d,
0x20, 0x8b, 0xc1, 0x99, 0xe8, 0x7e, 0x01, 0x83, 0xeb, 0x3a, 0x66, 0xa1,
0x1c, 0x7c, 0x66, 0x3b, 0x07, 0x8a, 0x57, 0xfc, 0x75, 0x06, 0x80, 0xca,
0x02, 0x88, 0x56, 0x02, 0x80, 0xc3, 0x10, 0x73, 0xed, 0x33, 0xc9, 0xfe,
0x06, 0xd8, 0x7d, 0x8a, 0x46, 0x10, 0x98, 0xf7, 0x66, 0x16, 0x03, 0x46,
0x1c, 0x13, 0x56, 0x1e, 0x03, 0x46, 0x0e, 0x13, 0xd1, 0x8b, 0x76, 0x11,
0x60, 0x89, 0x46, 0xfc, 0x89, 0x56, 0xfe, 0xb8, 0x20, 0x00, 0xf7, 0xe6,
0x8b, 0x5e, 0x0b, 0x03, 0xc3, 0x48, 0xf7, 0xf3, 0x01, 0x46, 0xfc, 0x11,
0x4e, 0xfe, 0x61, 0xbf, 0x00, 0x07, 0xe8, 0x28, 0x01, 0x72, 0x3e, 0x38,
0x2d, 0x74, 0x17, 0x60, 0xb1, 0x0b, 0xbe, 0xd8, 0x7d, 0xf3, 0xa6, 0x61,
0x74, 0x3d, 0x4e, 0x74, 0x09, 0x83, 0xc7, 0x20, 0x3b, 0xfb, 0x72, 0xe7,
0xeb, 0xdd, 0xfe, 0x0e, 0xd8, 0x7d, 0x7b, 0xa7, 0xbe, 0x7f, 0x7d, 0xac,
0x98, 0x03, 0xf0, 0xac, 0x98, 0x40, 0x74, 0x0c, 0x48, 0x74, 0x13, 0xb4,
0x0e, 0xbb, 0x07, 0x00, 0xcd, 0x10, 0xeb, 0xef, 0xbe, 0x82, 0x7d, 0xeb,
0xe6, 0xbe, 0x80, 0x7d, 0xeb, 0xe1, 0xcd, 0x16, 0x5e, 0x1f, 0x66, 0x8f,
0x04, 0xcd, 0x19, 0xbe, 0x81, 0x7d, 0x8b, 0x7d, 0x1a, 0x8d, 0x45, 0xfe,
0x8a, 0x4e, 0x0d, 0xf7, 0xe1, 0x03, 0x46, 0xfc, 0x13, 0x56, 0xfe, 0xb1,
0x04, 0xe8, 0xc2, 0x00, 0x72, 0xd7, 0xea, 0x00, 0x02, 0x70, 0x00, 0x52,
0x50, 0x06, 0x53, 0x6a, 0x01, 0x6a, 0x10, 0x91, 0x8b, 0x46, 0x18, 0xa2,
0x26, 0x05, 0x96, 0x92, 0x33, 0xd2, 0xf7, 0xf6, 0x91, 0xf7, 0xf6, 0x42,
0x87, 0xca, 0xf7, 0x76, 0x1a, 0x8a, 0xf2, 0x8a, 0xe8, 0xc0, 0xcc, 0x02,
0x0a, 0xcc, 0xb8, 0x01, 0x02, 0x80, 0x7e, 0x02, 0x0e, 0x75, 0x04, 0xb4,
0x42, 0x8b, 0xf4, 0x8a, 0x56, 0x24, 0xcd, 0x13, 0x61, 0x61, 0x72, 0x0a,
0x40, 0x75, 0x01, 0x42, 0x03, 0x5e, 0x0b, 0x49, 0x75, 0x77, 0xc3, 0x03,
0x18, 0x01, 0x27, 0x0d, 0x0a, 0x49, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64,
0x20, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x20, 0x64, 0x69, 0x73, 0x6b,
0xff, 0x0d, 0x0a, 0x44, 0x69, 0x73, 0x6b, 0x20, 0x49, 0x2f, 0x4f, 0x20,
0x65, 0x72, 0x72, 0x6f, 0x72, 0xff, 0x0d, 0x0a, 0x52, 0x65, 0x70, 0x6c,
0x61, 0x63, 0x65, 0x20, 0x74, 0x68, 0x65, 0x20, 0x64, 0x69, 0x73, 0x6b,
0x2c, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x74, 0x68, 0x65, 0x6e, 0x20, 0x70,
0x72, 0x65, 0x73, 0x73, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x6b, 0x65, 0x79,
0x0d, 0x0a, 0x00, 0x00, 0x49, 0x4f, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x53, 0x59, 0x53, 0x4d, 0x53, 0x44, 0x4f, 0x53, 0x20, 0x20, 0x20, 0x53,
0x59, 0x53, 0x7f, 0x01, 0x00, 0x41, 0xbb, 0x00, 0x07, 0x60, 0x66, 0x6a,
0x00, 0xe9, 0x3b, 0xff, 0x00, 0x00, 0x55, 0xaa
};
| 2,825 |
C
|
.h
| 40 | 67.4 | 73 | 0.654813 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,970 |
mbr_msg_rufus.h
|
pbatard_rufus/src/ms-sys/inc/mbr_msg_rufus.h
|
/*
* Rufus message MBR - Displays an ASCII text message contained in the
* 4 KB of sectors starting at LBA 34 (i.e. after the primary GPT if any).
* See https://github.com/pbatard/rufus/tree/master/res/mbr
* Copyright © 2019-2022 Pete Batard <[email protected]>
*/
unsigned char mbr_msg_rufus_0x0[] = {
0x41, 0x4B, 0x45, 0x4F, 0xFC, 0x31, 0xC0, 0xFA, 0x8E, 0xD0, 0xBC, 0x00,
0x7C, 0xFB, 0x8E, 0xD8, 0xBB, 0x13, 0x04, 0x8B, 0x07, 0x83, 0xE8, 0x04,
0x89, 0x07, 0xC1, 0xE0, 0x06, 0x8E, 0xC0, 0xB8, 0x03, 0x00, 0xCD, 0x10,
0xB4, 0x02, 0xCD, 0x10, 0xB4, 0x41, 0xBB, 0xAA, 0x55, 0x31, 0xC9, 0x31,
0xD2, 0xCD, 0x13, 0x72, 0x27, 0x81, 0xFB, 0x55, 0xAA, 0x75, 0x21, 0xF7,
0xC1, 0x01, 0x00, 0x74, 0x1B, 0x66, 0x31, 0xC0, 0x66, 0x50, 0x6A, 0x22,
0x06, 0x66, 0x50, 0x6A, 0x08, 0x6A, 0x10, 0x89, 0xE6, 0xB4, 0x42, 0xCD,
0x13, 0x9F, 0x83, 0xC4, 0x10, 0x9E, 0xEB, 0x0D, 0xB8, 0x08, 0x02, 0xB9,
0x23, 0x00, 0xBA, 0x80, 0x00, 0x31, 0xDB, 0xCD, 0x13, 0xBB, 0x07, 0x00,
0x72, 0x0B, 0x31, 0xF6, 0x8C, 0xC0, 0x8E, 0xD8, 0xE8, 0x3F, 0x00, 0xEB,
0x06, 0xBE, 0x0B, 0x7D, 0xE8, 0x37, 0x00, 0x31, 0xC0, 0x8E, 0xD8, 0xBE,
0x57, 0x7D, 0xE8, 0x2D, 0x00, 0xE8, 0x1D, 0x00, 0xB4, 0x01, 0xCD, 0x16,
0x75, 0x08, 0xB4, 0x02, 0xCD, 0x16, 0x24, 0x04, 0x74, 0xF2, 0x31, 0xC0,
0x8E, 0xD8, 0xB8, 0x34, 0x12, 0xA3, 0x73, 0x04, 0xEA, 0x00, 0x00, 0xFF,
0xFF, 0xB4, 0x01, 0xCD, 0x16, 0x74, 0x06, 0xB4, 0x00, 0xCD, 0x16, 0xE2,
0xF4, 0xC3, 0xAC, 0x3C, 0x00, 0x74, 0x4F, 0x3C, 0x0D, 0x74, 0xF7, 0x3C,
0x0A, 0x75, 0x10, 0x53, 0xB4, 0x03, 0xCD, 0x10, 0xFE, 0xC6, 0xB2, 0x00,
0xB4, 0x02, 0xCD, 0x10, 0x5B, 0xEB, 0xE3, 0x3C, 0x5C, 0x75, 0x1C, 0xB1,
0x02, 0xAC, 0x3C, 0x46, 0x7F, 0xD8, 0x2C, 0x30, 0x3C, 0x09, 0x7E, 0x02,
0x2C, 0x07, 0xC0, 0xE3, 0x04, 0x24, 0x0F, 0x08, 0xC3, 0xFE, 0xC9, 0x75,
0xE8, 0xEB, 0xC3, 0xB9, 0x01, 0x00, 0xB4, 0x09, 0xCD, 0x10, 0x53, 0x31,
0xDB, 0xB4, 0x03, 0xCD, 0x10, 0xFE, 0xC2, 0xB4, 0x02, 0xCD, 0x10, 0x5B,
0xEB, 0xAC, 0xC3, 0x0D, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x5C, 0x30, 0x34, 0x2A, 0x2A, 0x2A,
0x20, 0x45, 0x52, 0x52, 0x4F, 0x52, 0x3A, 0x20, 0x54, 0x48, 0x49, 0x53,
0x20, 0x4D, 0x45, 0x44, 0x49, 0x41, 0x20, 0x43, 0x41, 0x4E, 0x4E, 0x4F,
0x54, 0x20, 0x42, 0x4F, 0x4F, 0x54, 0x20, 0x49, 0x4E, 0x20, 0x4C, 0x45,
0x47, 0x41, 0x43, 0x59, 0x20, 0x4D, 0x4F, 0x44, 0x45, 0x20, 0x2A, 0x2A,
0x2A, 0x5C, 0x30, 0x37, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x0D, 0x0A, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x5C, 0x37, 0x30, 0x50, 0x6C, 0x65, 0x61, 0x73, 0x65, 0x20, 0x72, 0x65,
0x6D, 0x6F, 0x76, 0x65, 0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x6D, 0x65,
0x64, 0x69, 0x61, 0x20, 0x61, 0x6E, 0x64, 0x20, 0x70, 0x72, 0x65, 0x73,
0x73, 0x20, 0x61, 0x6E, 0x79, 0x20, 0x6B, 0x65, 0x79, 0x20, 0x74, 0x6F,
0x20, 0x72, 0x65, 0x62, 0x6F, 0x6F, 0x74, 0x5C, 0x30, 0x37, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
| 2,935 |
C
|
.h
| 44 | 64.75 | 74 | 0.672664 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
4,971 |
br_fat32pe_0x3f0.h
|
pbatard_rufus/src/ms-sys/inc/br_fat32pe_0x3f0.h
|
unsigned char br_fat32pe_0x3f0[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x55, 0xaa, 0xfa, 0x66, 0x0f, 0xb6, 0x46, 0x10, 0x66, 0x8b,
0x4e, 0x24, 0x66, 0xf7, 0xe1, 0x66, 0x03, 0x46, 0x1c, 0x66, 0x0f, 0xb7,
0x56, 0x0e, 0x66, 0x03, 0xc2, 0x33, 0xc9, 0x66, 0x89, 0x46, 0xfc, 0x66,
0xc7, 0x46, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xfa, 0x66, 0x8b, 0x46, 0x2c,
0x66, 0x83, 0xf8, 0x02, 0x0f, 0x82, 0xcf, 0xfc, 0x66, 0x3d, 0xf8, 0xff,
0xff, 0x0f, 0x0f, 0x83, 0xc5, 0xfc, 0x66, 0x0f, 0xa4, 0xc2, 0x10, 0xfb,
0x52, 0x50, 0xfa, 0x66, 0xc1, 0xe0, 0x10, 0x66, 0x0f, 0xac, 0xd0, 0x10,
0x66, 0x83, 0xe8, 0x02, 0x66, 0x0f, 0xb6, 0x5e, 0x0d, 0x8b, 0xf3, 0x66,
0xf7, 0xe3, 0x66, 0x03, 0x46, 0xfc, 0x66, 0x0f, 0xa4, 0xc2, 0x10, 0xfb,
0xbb, 0x00, 0x07, 0x8b, 0xfb, 0xb9, 0x01, 0x00, 0xe8, 0xbe, 0xfc, 0x0f,
0x82, 0xaa, 0xfc, 0x38, 0x2d, 0x74, 0x1e, 0xb1, 0x0b, 0x56, 0xbe, 0xd8,
0x7d, 0xf3, 0xa6, 0x5e, 0x74, 0x19, 0x03, 0xf9, 0x83, 0xc7, 0x15, 0x3b,
0xfb, 0x72, 0xe8, 0x4e, 0x75, 0xd6, 0x58, 0x5a, 0xe8, 0x66, 0x00, 0x72,
0xab, 0x83, 0xc4, 0x04, 0xe9, 0x64, 0xfc, 0x83, 0xc4, 0x04, 0x8b, 0x75,
0x09, 0x8b, 0x7d, 0x0f, 0x8b, 0xc6, 0xfa, 0x66, 0xc1, 0xe0, 0x10, 0x8b,
0xc7, 0x66, 0x83, 0xf8, 0x02, 0x72, 0x3b, 0x66, 0x3d, 0xf8, 0xff, 0xff,
0x0f, 0x73, 0x33, 0x66, 0x48, 0x66, 0x48, 0x66, 0x0f, 0xb6, 0x4e, 0x0d,
0x66, 0xf7, 0xe1, 0x66, 0x03, 0x46, 0xfc, 0x66, 0x0f, 0xa4, 0xc2, 0x10,
0xfb, 0xbb, 0x00, 0x07, 0x53, 0xb9, 0x04, 0x00, 0xe8, 0x52, 0xfc, 0x5b,
0x0f, 0x82, 0x3d, 0xfc, 0x81, 0x3f, 0x4d, 0x5a, 0x75, 0x08, 0x81, 0xbf,
0x00, 0x02, 0x42, 0x4a, 0x74, 0x06, 0xbe, 0x80, 0x7d, 0xe9, 0x0e, 0xfc,
0xea, 0x00, 0x02, 0x70, 0x00, 0x03, 0xc0, 0x13, 0xd2, 0x03, 0xc0, 0x13,
0xd2, 0xe8, 0x18, 0x00, 0xfa, 0x26, 0x66, 0x8b, 0x01, 0x66, 0x25, 0xff,
0xff, 0xff, 0x0f, 0x66, 0x0f, 0xa4, 0xc2, 0x10, 0x66, 0x3d, 0xf8, 0xff,
0xff, 0x0f, 0xfb, 0xc3, 0xbf, 0x00, 0x7e, 0xfa, 0x66, 0xc1, 0xe0, 0x10,
0x66, 0x0f, 0xac, 0xd0, 0x10, 0x66, 0x0f, 0xb7, 0x4e, 0x0b, 0x66, 0x33,
0xd2, 0x66, 0xf7, 0xf1, 0x66, 0x3b, 0x46, 0xf8, 0x74, 0x44, 0x66, 0x89,
0x46, 0xf8, 0x66, 0x03, 0x46, 0x1c, 0x66, 0x0f, 0xb7, 0x4e, 0x0e, 0x66,
0x03, 0xc1, 0x66, 0x0f, 0xb7, 0x5e, 0x28, 0x83, 0xe3, 0x0f, 0x74, 0x16,
0x3a, 0x5e, 0x10, 0x0f, 0x83, 0xa4, 0xfb, 0x52, 0x66, 0x8b, 0xc8, 0x66,
0x8b, 0x46, 0x24, 0x66, 0xf7, 0xe3, 0x66, 0x03, 0xc1, 0x5a, 0x52, 0x66,
0x0f, 0xa4, 0xc2, 0x10, 0xfb, 0x8b, 0xdf, 0xb9, 0x01, 0x00, 0xe8, 0xb4,
0xfb, 0x5a, 0x0f, 0x82, 0x9f, 0xfb, 0xfb, 0x8b, 0xda, 0xc3, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0xaa
};
| 3,295 |
C
|
.h
| 46 | 68.717391 | 73 | 0.658049 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
4,972 |
file.h
|
pbatard_rufus/src/ms-sys/inc/file.h
|
#ifndef FILE_H
#define FILE_H
#include <stdint.h>
/* Max valid value of uiLen for contains_data */
#define MAX_DATA_LEN 65536
/* We hijack the FILE structure for our own needs */
typedef struct {
void *_handle;
uint64_t _offset;
} FAKE_FD;
/* Checks if a file contains a data pattern of length Len at position
Position. The file pointer will change when calling this function! */
int contains_data(FILE *fp, uint64_t Position,
const void *pData, uint64_t Len);
/* Reads data of length Len at position Position.
The file pointer will change when calling this function! */
int read_data(FILE *fp, uint64_t Position,
void *pData, uint64_t uiLen);
/* Writes a data pattern of length Len at position Position.
The file pointer will change when calling this function! */
int write_data(FILE *fp, uint64_t Position,
const void *pData, uint64_t Len);
/* Writes nSectors of size SectorSize starting at sector StartSector */
int64_t write_sectors(void *hDrive, uint64_t SectorSize,
uint64_t StartSector, uint64_t nSectors,
const void *pBuf);
/* Reads nSectors of size SectorSize starting at sector StartSector */
int64_t read_sectors(void *hDrive, uint64_t SectorSize,
uint64_t StartSector, uint64_t nSectors,
void *pBuf);
#endif
| 1,370 |
C
|
.h
| 31 | 38.354839 | 72 | 0.694737 |
pbatard/rufus
| 28,236 | 2,528 | 13 |
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.