Executable not running in windows except when using terminal - windows

I'm using the SDL_TFF library and it compiles, but the executable doesn't run directly, except when I run it from the terminal. If I comment out the SDL_TFF code it runs normally.
Does anyone know what could be causing this problem?
Edit:
#include <stdio.h>
#include <SDL.h>
#include <SDL_ttf.h> //version 2.0.12
TTF_Font* Font;
SDL_DisplayMode Desktop_Display_Mode;
SDL_Window* Window;
SDL_Surface* Window_surface;
SDL_Renderer* Renderer;
bool load_font()
{
//Font = TTF_OpenFont("fonts\\NotoSans-Bold.ttf", 16);
Font = TTF_OpenFont("fonts\\NotoSansCJKjp-Bold.otf", 18);
if (Font == NULL)
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"Count not load font! TTF_Error: %s\n", TTF_GetError()
);
return false;
}
return true;
}
bool initialize()
{
// Initialize SDL Library
if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"SDL could not initialize! SDL_Error: %s\n", SDL_GetError()
);
return false;
}
// Initialize SDL_ttf library
if (TTF_Init() != 0)
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"SDL_ttf could not initialize! TTF_Error: %s\n", TTF_GetError()
);
return false;
}
// Load Font ---------------------------------------------------------------
if ( !load_font() )
{
return false;
}
// Get Desktop Display Mode
if (SDL_GetDesktopDisplayMode(0, &Desktop_Display_Mode) != 0)
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"SDL could not get Desktop Display Mode! SDL_Error: %s\n",
SDL_GetError()
);
return false;
}
// Create Window
Window = SDL_CreateWindow(
"SDL Test",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
Desktop_Display_Mode.w, Desktop_Display_Mode.h,
SDL_WINDOW_BORDERLESS //Flags
);
if( Window == NULL )
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"Window could not be created! SDL_Error: %s\n",
SDL_GetError()
);
return false;
}
Renderer = SDL_CreateRenderer( Window, -1,
SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC
);
if ( Renderer == NULL )
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"Renderer could not be created! SDL_Error: %s\n",
SDL_GetError()
);
return false;
}
return true;
}
bool clear_screen()
{
if ( SDL_SetRenderDrawColor( Renderer, 0x00, 0x00, 0x00, 0xFF ) != 0 )
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"Could not set render draw color! SDL_Error: %s\n",
SDL_GetError()
);
return false;
}
if ( SDL_RenderClear( Renderer ) != 0 )
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"Could not clear the renderer! SDL_Error: %s\n",
SDL_GetError()
);
return false;
}
return true;
}
int main( int argc, char* args[] )
{
SDL_Log("Started.");
bool running = initialize();
SDL_Color text_color = {255, 255, 255};
const char* text_string;
text_string = "A journey of a thousand miles begins with a single step.\n こんにちは";
SDL_Rect text_dest;
text_dest.x = 100;
text_dest.y = 100;
text_dest.w = 0;
text_dest.h = 0;
if ( TTF_SizeUTF8(Font, text_string, &text_dest.w, &text_dest.h) != 0)
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"Unable to get text size! TTF_Error: %s\n", TTF_GetError()
);
running = false;
}
SDL_Surface* text_surface = NULL;
text_surface = TTF_RenderUTF8_Solid(
Font,
text_string,
text_color
);
if ( text_surface == NULL )
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"Unable to render text! SDL_Error: %s\n",
TTF_GetError()
);
running = false;
}
SDL_Texture* text_texture = NULL;
text_texture = SDL_CreateTextureFromSurface( Renderer, text_surface );
if ( text_texture == NULL )
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"Unable to render text! SDL_Error: %s\n",
TTF_GetError()
);
running = false;
}
// MAIN LOOP ===============================================================
SDL_Event event;
while (running)
{
// Clear the screen
if ( !clear_screen() )
{
break;
}
// Check for events
if (SDL_PollEvent( &event))
{
// Check for the quit event
if (event.type == SDL_QUIT)
{
SDL_Log("Quit.");
break;
}
}
// Apply the text
if ( SDL_RenderCopy( Renderer, text_texture, NULL, &text_dest ) != 0 )
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"Unable to draw text! SDL_Error: %s\n",
SDL_GetError()
);
break;
}
//Update Window
SDL_RenderPresent( Renderer );
}
//Destroy Window
SDL_DestroyWindow( Window );
SDL_DestroyRenderer( Renderer);
//Quit SDL subsystems
TTF_Quit();
SDL_Quit();
SDL_Log("Ended.");
return 0;
}
Edit2: I tested more thorougly and it seems that the function TTF_OpenFont() is causing the problem. As long as I don't call that function the exe will run normally.

SOLVED!
It was the way I was executing the program from command line: "\bin\myprog.exe"
Thus the relative filepath was incorrect because "\bin\fonts..." did not exist. As I have not implemented SDL_LogSetOutputFunction to write logs to a file and std out is apparently suppressed I could not see that I must have been getting error messages indicating that the file was not being loaded.

Related

CreateFileA Visit a windows file system driver returned INVALID_HANDLE_VALUE

I writed a file system demo most likely fast fat ,but when I use CreateFileA to call my dirver ,it gives an INVALID_HANDLE_VALUE result . I have checked the driver `s IRP dispatches and found no DbgPrint setting in the function entries triggered .
This is the user mode code:
public IntPtr LoadDriver(string lpFileName)
{
int error = 0;
string openName = string.Format("\\\\.\\{0}", EXE_DRIVER_NAME);
IntPtr hSCManager = WinAPI.OpenSCManager(null, null,
WinAPI.SC_MANAGER_CREATE_SERVICE);
if (IntPtr.Zero != hSCManager)
{
//创建服务
IntPtr hService = WinAPI.CreateService(hSCManager, EXE_DRIVER_NAME,
DISPLAY_NAME, WinAPI.SERVICE_START,
WinAPI.SERVICE_KERNEL_DRIVER, WinAPI.SERVICE_DEMAND_START,
WinAPI.SERVICE_ERROR_IGNORE, lpFileName, null, IntPtr.Zero, null, null, null);
if (WinAPI.ERROR_SERVICE_EXISTS == WinAPI.GetLastError())
{
hService = WinAPI.OpenService(hSCManager, EXE_DRIVER_NAME, WinAPI.SERVICE_START);
}
error = WinAPI.GetLastError();
if(error!=0)
{
dumpErrorCode("OpenService失败 ", error);
}
int startflag = WinAPI.StartService(hService, 0, 0);
if (startflag == 0)
{
error = WinAPI.GetLastError();
if (error != WinAPI.ERROR_SERVICE_ALREADY_RUNNING) //已经启动
{
dumpErrorCode("StartService失败", error);
}
else
{
MessageBox.Show("服务已经启动");
}
}
// WinAPI.CloseServiceHandle(hService);
// WinAPI.CloseServiceHandle(hSCManager);
MessageBox.Show(openName);
try
{
hDriver = WinAPI.CreateFileA(openName, WinAPI.GENERIC_READ , 0, IntPtr.Zero, WinAPI.OPEN_EXISTING, null, IntPtr.Zero);
if (hDriver == (IntPtr)(-1))
{
dumpErrorCode("获取文件句柄失败 ", error);
}
else
{
MessageBox.Show("成功创建驱动");
//his.OpenDriverEvent();
}
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
return hDriver;
}
This is the driver`s entry point code:
NTSTATUS
DriverEntry(
_In_ PDRIVER_OBJECT DriverObject,
_In_ PUNICODE_STRING RegistryPath
)
{
NTSTATUS Status;
UNICODE_STRING UnicodeString;
FS_FILTER_CALLBACKS FilterCallbacks;
UNREFERENCED_PARAMETER( RegistryPath );
DbgPrint("\nThis is HRFS Driver Entry\n");
RtlInitUnicodeString(&UnicodeString, L"\\fastFatDemo");
gSFilterDriverObject = DriverObject;
Status = IoCreateDevice( DriverObject,
0,
&UnicodeString,
FILE_DEVICE_DISK_FILE_SYSTEM,
0,
FALSE,
&HrfsDiskFileSystemDeviceObject );
if (!NT_SUCCESS( Status )) {
return Status;
}
DbgPrint("HRFS device HRFS created\n ");
DriverObject->DriverUnload = FatUnload;
DriverObject->MajorFunction[IRP_MJ_CREATE] = (PDRIVER_DISPATCH)FatFsdCreate;
DriverObject->MajorFunction[IRP_MJ_CLOSE] = (PDRIVER_DISPATCH)HrfsFsdClose;
DriverObject->MajorFunction[IRP_MJ_READ] = (PDRIVER_DISPATCH)FatFsdRead;
DriverObject->MajorFunction[IRP_MJ_WRITE] = (PDRIVER_DISPATCH)FatFsdWrite;
DriverObject->MajorFunction[IRP_MJ_QUERY_INFORMATION] = (PDRIVER_DISPATCH)FatFsdQueryInformation;
DriverObject->MajorFunction[IRP_MJ_SET_INFORMATION] = (PDRIVER_DISPATCH)FatFsdSetInformation;
DriverObject->MajorFunction[IRP_MJ_QUERY_EA] = (PDRIVER_DISPATCH)FatFsdQueryEa;
DriverObject->MajorFunction[IRP_MJ_SET_EA] = (PDRIVER_DISPATCH)FatFsdSetEa;
DriverObject->MajorFunction[IRP_MJ_FLUSH_BUFFERS] = (PDRIVER_DISPATCH)FatFsdFlushBuffers;
DriverObject->MajorFunction[IRP_MJ_QUERY_VOLUME_INFORMATION] = (PDRIVER_DISPATCH)FatFsdQueryVolumeInformation;
DriverObject->MajorFunction[IRP_MJ_SET_VOLUME_INFORMATION] = (PDRIVER_DISPATCH)FatFsdSetVolumeInformation;
DriverObject->MajorFunction[IRP_MJ_CLEANUP] = (PDRIVER_DISPATCH)FatFsdCleanup;
DriverObject->MajorFunction[IRP_MJ_DIRECTORY_CONTROL] = (PDRIVER_DISPATCH)FatFsdDirectoryControl;
DriverObject->MajorFunction[IRP_MJ_FILE_SYSTEM_CONTROL] = (PDRIVER_DISPATCH)FatFsdFileSystemControl;
DriverObject->MajorFunction[IRP_MJ_LOCK_CONTROL] = (PDRIVER_DISPATCH)FatFsdLockControl;
DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = (PDRIVER_DISPATCH)FatFsdDeviceControl;
DriverObject->MajorFunction[IRP_MJ_SHUTDOWN] = (PDRIVER_DISPATCH)FatFsdShutdown;
DriverObject->MajorFunction[IRP_MJ_PNP] = (PDRIVER_DISPATCH)FatFsdPnp;
DbgPrint("HRFS device HRFS MajorFunction created\n ");
DriverObject->FastIoDispatch = NULL;
DbgPrint("HRFS device HRFS FatFastIoDispatch created\n ");
RtlZeroMemory(&FatFastIoDispatch, sizeof(FatFastIoDispatch));
FatFastIoDispatch.SizeOfFastIoDispatch = sizeof(FAST_IO_DISPATCH);
FatFastIoDispatch.FastIoCheckIfPossible = FALSE; // CheckForFastIo
FatFastIoDispatch.FastIoRead = FALSE; // Read
FatFastIoDispatch.FastIoWrite = FALSE; // Write
FatFastIoDispatch.FastIoQueryBasicInfo = FALSE; // QueryBasicInfo
FatFastIoDispatch.FastIoQueryStandardInfo = FALSE; // QueryStandardInfo
FatFastIoDispatch.FastIoLock = FALSE; // Lock
FatFastIoDispatch.FastIoUnlockSingle = FALSE; // UnlockSingle
FatFastIoDispatch.FastIoUnlockAll = FALSE; // UnlockAll
FatFastIoDispatch.FastIoUnlockAllByKey = FALSE; // UnlockAllByKey
FatFastIoDispatch.FastIoQueryNetworkOpenInfo = FALSE;
FatFastIoDispatch.AcquireForCcFlush = FALSE;
FatFastIoDispatch.ReleaseForCcFlush = FALSE;
FatFastIoDispatch.MdlRead = FALSE;
FatFastIoDispatch.MdlReadComplete = FALSE;
FatFastIoDispatch.PrepareMdlWrite = FALSE;
FatFastIoDispatch.MdlWriteComplete = FALSE;
//FatFastIoDispatch.SizeOfFastIoDispatch = sizeof(FAST_IO_DISPATCH);
//FatFastIoDispatch.FastIoCheckIfPossible = FatFastIoCheckIfPossible; // CheckForFastIo
//FatFastIoDispatch.FastIoRead = FsRtlCopyRead; // Read
//FatFastIoDispatch.FastIoWrite = FsRtlCopyWrite; // Write
//FatFastIoDispatch.FastIoQueryBasicInfo = FatFastQueryBasicInfo; // QueryBasicInfo
//FatFastIoDispatch.FastIoQueryStandardInfo = FatFastQueryStdInfo; // QueryStandardInfo
//FatFastIoDispatch.FastIoLock = FatFastLock; // Lock
//FatFastIoDispatch.FastIoUnlockSingle = FatFastUnlockSingle; // UnlockSingle
//FatFastIoDispatch.FastIoUnlockAll = FatFastUnlockAll; // UnlockAll
//FatFastIoDispatch.FastIoUnlockAllByKey = FatFastUnlockAllByKey; // UnlockAllByKey
//FatFastIoDispatch.FastIoQueryNetworkOpenInfo = FatFastQueryNetworkOpenInfo;
//FatFastIoDispatch.AcquireForCcFlush = HrfsAcquireForCcFlush;
//FatFastIoDispatch.ReleaseForCcFlush = HrfsReleaseForCcFlush;
//FatFastIoDispatch.MdlRead = FsRtlMdlReadDev;
//FatFastIoDispatch.MdlReadComplete = FsRtlMdlReadCompleteDev;
//FatFastIoDispatch.PrepareMdlWrite = FsRtlPrepareMdlWriteDev;
//FatFastIoDispatch.MdlWriteComplete = FsRtlMdlWriteCompleteDev;
/* FsFilter通知回调例程在下层文件系统执行某些操作之前或之后调用。
如果需要获取更多有关于FsFilter回调例程相关信息,可参见FsRtlRegisterFileSystemFilterCallbacks例程
为了注册FsFilter的通知回调例程必须分配并初始化FS_FILTER_CALLBACKS结构体,然后向该结构体中促出FsFilter回调例程,
并将存储有Callbacks parameter到FsRtlRegisterFileSystemFilterCallbacks中。*/
RtlZeroMemory( &FilterCallbacks,
sizeof(FS_FILTER_CALLBACKS) );
FilterCallbacks.SizeOfFsFilterCallbacks = sizeof(FS_FILTER_CALLBACKS);
FilterCallbacks.PreAcquireForSectionSynchronization = HrfsFilterCallbackAcquireForCreateSection;
Status = FsRtlRegisterFileSystemFilterCallbacks( DriverObject,
&FilterCallbacks );
if (!NT_SUCCESS( Status )) {
IoDeleteDevice( HrfsDiskFileSystemDeviceObject );
return Status;
}
DbgPrint("HRFS device HRFS FilterCallbacks registed\n ");
RtlZeroMemory( &HrfsData, sizeof(FAT_DATA));
HrfsData.NodeTypeCode = HRFS_NTC_DATA_HEADER;
HrfsData.NodeByteSize = sizeof(FAT_DATA);
InitializeListHead(&HrfsData.VcbQueue);
pDriverObject = DriverObject;
HrfsData.DiskFileSystemDeviceObject = HrfsDiskFileSystemDeviceObject;
//
// This list head keeps track of closes yet to be done.
//
InitializeListHead( &HrfsData.AsyncCloseList );
InitializeListHead( &HrfsData.DelayedCloseList );
HrfsData.FatCloseItem = IoAllocateWorkItem( HrfsDiskFileSystemDeviceObject);
if (HrfsData.FatCloseItem == NULL) {
IoDeleteDevice (HrfsDiskFileSystemDeviceObject);
return STATUS_INSUFFICIENT_RESOURCES;
}
DbgPrint("HRFS device HRFS workitem created\n ");
//
// Allocate the zero page
//
HrfsData.ZeroPage = ExAllocatePoolWithTag( NonPagedPoolNx, PAGE_SIZE, 'ZtaF' );
if (HrfsData.ZeroPage == NULL) {
IoDeleteDevice (HrfsDiskFileSystemDeviceObject);
return STATUS_INSUFFICIENT_RESOURCES;
}
RtlZeroMemory( HrfsData.ZeroPage, PAGE_SIZE );
//
// Now initialize our general purpose spinlock (gag) and figure out how
// deep and wide we want our delayed lists (along with fooling ourselves
// about the lookaside depths).
//
KeInitializeSpinLock( &HrfsData.GeneralSpinLock );
HrfsData.CacheManagerCallbacks.AcquireForLazyWrite = &HrfsAcquireFcbForLazyWrite;
HrfsData.CacheManagerCallbacks.ReleaseFromLazyWrite = &HrfsReleaseFcbFromLazyWrite;
HrfsData.CacheManagerCallbacks.AcquireForReadAhead = &HrfsAcquireFcbForReadAhead;
HrfsData.CacheManagerCallbacks.ReleaseFromReadAhead = &HrfsReleaseFcbFromReadAhead;
HrfsData.CacheManagerNoOpCallbacks.AcquireForLazyWrite = &HrfsNoOpAcquire;
HrfsData.CacheManagerNoOpCallbacks.ReleaseFromLazyWrite = &HrfsNoOpRelease;
HrfsData.CacheManagerNoOpCallbacks.AcquireForReadAhead = &HrfsNoOpAcquire;
HrfsData.CacheManagerNoOpCallbacks.ReleaseFromReadAhead = &HrfsNoOpRelease;
//
// Set up global pointer to our process.
//
HrfsData.OurProcess = PsGetCurrentProcess();
DbgPrint("HRFS device HRFS our process getted\n ");
//
// Setup the number of processors we support for statistics as the current number
// running.
//
#if (NTDDI_VERSION >= NTDDI_VISTA)
HrfsData.NumberProcessors = KeQueryActiveProcessorCount( NULL );
#else
HrfsData.NumberProcessors = KeNumberProcessors;
#endif
DbgPrint("HrfsData.NumberProcessors :%d", HrfsData.NumberProcessors);
ExInitializeResourceLite( &HrfsData.Resource );
IoRegisterFileSystem(HrfsDiskFileSystemDeviceObject);
ObReferenceObject (HrfsDiskFileSystemDeviceObject);
DbgPrint("Device HRFS HrfsDiskFileSystemDeviceObject registed\n ");
return( STATUS_SUCCESS );
}

Handle SDL_KeyboardEvent without window focus

I'm trying to get keyboard events using SDL2.0. The following sample is working for me when I have the window's focus:
#include <SDL2/SDL.h>
int main(int argc, char* argv[])
{
if (SDL_Init(SDL_INIT_VIDEO) != 0) /* Prefer only events SDL_INIT_EVENTS */
{
SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
return 1;
}
SDL_Window* gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 320, SDL_WINDOW_SHOWN ); /* I don't want this window! */
/* While no quit */
bool quit = false;
//Event handler
SDL_Event e;
//While application is running
while( !quit )
{
//Handle events on queue
while( SDL_PollEvent( &e ) != 0 )
{
//User requests quit
if( e.type == SDL_QUIT )
{
quit = true;
}
//User presses a key
else if( e.type == SDL_KEYDOWN )
{
printf( "Key type: %d\n", e.key.keysym.sym );
//Select surfaces based on key press
switch( e.key.keysym.sym )
{
case SDLK_UP:
printf( "UP!\n" );
break;
case SDLK_DOWN:
printf( "DOWN!\n" );
break;
case SDLK_LEFT:
printf( "LEFT!\n" );
break;
case SDLK_RIGHT:
printf( "RIGHT!\n" );
break;
default:
break;
}
}
}
}
SDL_Quit();
return 0;
}
I would like to avoid use SDL_Init(SDL_INIT_VIDEO) without create a SDL_Window using only SDL_Init(SDL_INIT_EVENTS). Actually, my problem is that I only can receive the events if I create the windows and focus it. Is it possible to get the events globally without the focus?
My strategy is to try to use SDL library to isolate OS events behavior and focus in record/play small events provided by an user. Other suggests are welcome.

FFMPEG: avcodec_send_packet(); error while using multithread

I wrote 2 threads to decode RTSP stream from IP camera as below:
RTSP_read_paket function used to read Packets from RTSP link, packets stored in a queue named Packet_buf.
std::queue<AVPacket> Packet_buf;
bool pkt_pending_k = false;
int RTSP_read_packet (string url)
{
rtsp_init(url);
int ret;
AVPacket packet;
av_init_packet(&packet);
while(1)
{
ret = av_read_frame(pFormatCtx,&packet);
if(ret==0)
{
if (packet.stream_index == video_stream_index)
{
Packet_buf.push(packet);
if((ready1 == false))
{
ready1 = true;
conv1.notify_one();
}
}
av_packet_unref(&packet);
cout<<"number of RTSP packet: "<<Packet_buf.size()<<endl;
}
}
return 0;
}
ffmpeg_decode read packets from Packet_buf to decode frames
AVFrame ffmpeg_decode( void )
{
AVPacket avpkt;
av_init_packet(&avpkt);
int ret;
conv1.wait(lk1,[]{return ready1;});
while(1)
{
while(1)
{
ret = avcodec_receive_frame(pCodecCtx,pFrame);
if(ret == AVERROR(EAGAIN)||ret==AVERROR_EOF){
break;
}
return pFrame;
}
if(!Packet_buf.empty())
{
if(pkt_pending_k == false)
{
avpkt = Packet_buf.front();
Packet_buf.pop();
}else{
pkt_pending_k = false;
}
}
ret = avcodec_send_packet(pCodecCtx, &avpkt); //program halting here
cout<<"-------------> ret = "<<ret<<endl;
if(ret==AVERROR(EAGAIN))
{
pkt_pending_k = true;
}
if(ret<0||ret==AVERROR_EOF)
{
cout<<"avcodec_send_packet: "<<ret<<endl;
break;
}
}
}
int main () {
thread Camera2_readPackets(RTSP_read_packet,url);
thread Camera2_decode(ffmpeg_decode,url);
Camera2_decode.join();
return 0;
}
My program halt at line:
ret = avcodec_send_packet(pCodecCtx, &avpkt);
Anyone can help me find the problem, thanks !
P/s:
rtsp_init function:
int rtsp_init (string url)
{
av_register_all();
avdevice_register_all();
avcodec_register_all();
avformat_network_init();
const char *filenameSrc = url.c_str();
pFormatCtx = avformat_alloc_context();
if ( pFormatCtx == NULL )
return -8;
AVDictionary *options = NULL;
av_dict_set(&options,"rtsp_flags","prefer_tcp",0);
av_dict_set(&options,"stimeout","1000000",0);
int avret = avformat_open_input( &pFormatCtx, filenameSrc, NULL, &options );
av_dict_free(&options);
if ( avret != 0 ) {
std::cout << "Open File Error 12" << std::endl;
return -12;
}
avret = avformat_find_stream_info( pFormatCtx, NULL );
if ( avret < 0 ) {
std::cout << "Get Stream Information Error 13" << std::endl;
avformat_close_input( &pFormatCtx );
pFormatCtx = NULL;
return -13;
}
av_dump_format( pFormatCtx, 0, filenameSrc, 0 );
video_stream_index = av_find_best_stream(pFormatCtx,AVMEDIA_TYPE_VIDEO,-1,-1,NULL,0);
if ( video_stream_index < 0 ) {
std::cout << "Video stream was not found Error 14" << std::endl;
avformat_close_input( &pFormatCtx );
pFormatCtx = NULL;
return -14;
}
pCodecCtx = avcodec_alloc_context3(NULL);
avret = avcodec_parameters_to_context(pCodecCtx,pFormatCtx->streams[video_stream_index]->codecpar);
if(avret<0)
{
std::cout << "codec not found Error 15" << std::endl;
return -15;
}
pCodec = avcodec_find_decoder( pCodecCtx->codec_id );
avret = avcodec_open2( pCodecCtx, pCodec, NULL );
if ( avret < 0) {
std::cout << "Open Codec Error 16" << std::endl;
return -16;
}
pFrame = av_frame_alloc();
pFrameRGB = av_frame_alloc();
pFrame->width = pCodecCtx->width;
pFrame->height = pCodecCtx->height;
pFrame->format = pCodecCtx->pix_fmt;
avret = av_frame_get_buffer(pFrame,0);
if (avret < 0)
{
return -17;
}
pFrameRGB->width = pCodecCtx->width;
pFrameRGB->height = pCodecCtx->height;
pFrameRGB->format = AV_PIX_FMT_BGR24;
avret = av_frame_get_buffer(pFrameRGB, 0);
if (avret < 0)
{
return -18;
}
return ( EXIT_SUCCESS );
}

ffmpeg avcodec_encode_video2 hangs when using Quick Sync h264_qsv encoder

When I use the mpeg4 or h264 encoders, I am able to successfully encode images to make a valid AVI file using the API for ffmpeg 3.1.0. However, when I use the Quick Sync encoder (h264_qsv), avcodec_encode_video2 will hang some of the time. I found that when using images that are 1920x1080, it was rare that avcodec_encode_video2 would hang. When using 256x256 images, it was very likely that the function would hang.
I have created the test code below that demonstrates the hang of avcodec_encode_video2. The code will create a 1000 frame, 256x256 AVI with a bit rate of 400000. The frames are simply allocated, so the output video should just be green frames.
The problem was observed using Windows 7 and Windows 10, using the 32-bit or 64-bit test application.
If anyone has any idea on how I can avoid the avcodec_encode_video2 hang I would be very grateful! Thanks in advance for any assistance.
extern "C"
{
#ifndef __STDC_CONSTANT_MACROS
#define __STDC_CONSTANT_MACROS
#endif
#include "avcodec.h"
#include "avformat.h"
#include "swscale.h"
#include "avutil.h"
#include "imgutils.h"
#include "opt.h"
#include <rational.h>
}
#include <iostream>
// Globals
AVCodec* m_pCodec = NULL;
AVStream *m_pStream = NULL;
AVOutputFormat* m_pFormat = NULL;
AVFormatContext* m_pFormatContext = NULL;
AVCodecContext* m_pCodecContext = NULL;
AVFrame* m_pFrame = NULL;
int m_frameIndex;
// Output format
AVPixelFormat m_pixType = AV_PIX_FMT_NV12;
// Use for mpeg4
//AVPixelFormat m_pixType = AV_PIX_FMT_YUV420P;
// Output frame rate
int m_frameRate = 30;
// Output image dimensions
int m_imageWidth = 256;
int m_imageHeight = 256;
// Number of frames to export
int m_frameCount = 1000;
// Output file name
const char* m_fileName = "c:/test/test.avi";
// Output file type
const char* m_fileType = "AVI";
// Codec name used to encode
const char* m_encoderName = "h264_qsv";
// use for mpeg4
//const char* m_encoderName = "mpeg4";
// Target bit rate
int m_targetBitRate = 400000;
void addVideoStream()
{
m_pStream = avformat_new_stream( m_pFormatContext, m_pCodec );
m_pStream->id = m_pFormatContext->nb_streams - 1;
m_pStream->time_base = m_pCodecContext->time_base;
m_pStream->codec->pix_fmt = m_pixType;
m_pStream->codec->flags = m_pCodecContext->flags;
m_pStream->codec->width = m_pCodecContext->width;
m_pStream->codec->height = m_pCodecContext->height;
m_pStream->codec->time_base = m_pCodecContext->time_base;
m_pStream->codec->bit_rate = m_pCodecContext->bit_rate;
}
AVFrame* allocatePicture( enum AVPixelFormat pix_fmt, int width, int height )
{
AVFrame *frame;
frame = av_frame_alloc();
if ( !frame )
{
return NULL;
}
frame->format = pix_fmt;
frame->width = width;
frame->height = height;
int checkImage = av_image_alloc( frame->data, frame->linesize, width, height, pix_fmt, 32 );
if ( checkImage < 0 )
{
return NULL;
}
return frame;
}
bool initialize()
{
AVRational frameRate;
frameRate.den = m_frameRate;
frameRate.num = 1;
av_register_all();
m_pCodec = avcodec_find_encoder_by_name(m_encoderName);
if( !m_pCodec )
{
return false;
}
m_pCodecContext = avcodec_alloc_context3( m_pCodec );
m_pCodecContext->width = m_imageWidth;
m_pCodecContext->height = m_imageHeight;
m_pCodecContext->time_base = frameRate;
m_pCodecContext->gop_size = 0;
m_pCodecContext->pix_fmt = m_pixType;
m_pCodecContext->codec_id = m_pCodec->id;
m_pCodecContext->bit_rate = m_targetBitRate;
av_opt_set( m_pCodecContext->priv_data, "+CBR", "", 0 );
return true;
}
bool startExport()
{
m_frameIndex = 0;
char fakeFileName[512];
int checkAllocContext = avformat_alloc_output_context2( &m_pFormatContext, NULL, m_fileType, fakeFileName );
if ( checkAllocContext < 0 )
{
return false;
}
if ( !m_pFormatContext )
{
return false;
}
m_pFormat = m_pFormatContext->oformat;
if ( m_pFormat->video_codec != AV_CODEC_ID_NONE )
{
addVideoStream();
int checkOpen = avcodec_open2( m_pCodecContext, m_pCodec, NULL );
if ( checkOpen < 0 )
{
return false;
}
m_pFrame = allocatePicture( m_pCodecContext->pix_fmt, m_pCodecContext->width, m_pCodecContext->height );
if( !m_pFrame )
{
return false;
}
m_pFrame->pts = 0;
}
int checkOpen = avio_open( &m_pFormatContext->pb, m_fileName, AVIO_FLAG_WRITE );
if ( checkOpen < 0 )
{
return false;
}
av_dict_set( &(m_pFormatContext->metadata), "title", "QS Test", 0 );
int checkHeader = avformat_write_header( m_pFormatContext, NULL );
if ( checkHeader < 0 )
{
return false;
}
return true;
}
int processFrame( AVPacket& avPacket )
{
avPacket.stream_index = 0;
avPacket.pts = av_rescale_q( m_pFrame->pts, m_pStream->codec->time_base, m_pStream->time_base );
avPacket.dts = av_rescale_q( m_pFrame->pts, m_pStream->codec->time_base, m_pStream->time_base );
m_pFrame->pts++;
int retVal = av_interleaved_write_frame( m_pFormatContext, &avPacket );
return retVal;
}
bool exportFrame()
{
int success = 1;
int result = 0;
AVPacket avPacket;
av_init_packet( &avPacket );
avPacket.data = NULL;
avPacket.size = 0;
fflush(stdout);
std::cout << "Before avcodec_encode_video2 for frame: " << m_frameIndex << std::endl;
success = avcodec_encode_video2( m_pCodecContext, &avPacket, m_pFrame, &result );
std::cout << "After avcodec_encode_video2 for frame: " << m_frameIndex << std::endl;
if( result )
{
success = processFrame( avPacket );
}
av_packet_unref( &avPacket );
m_frameIndex++;
return ( success == 0 );
}
void endExport()
{
int result = 0;
int success = 0;
if (m_pFrame)
{
while ( success == 0 )
{
AVPacket avPacket;
av_init_packet( &avPacket );
avPacket.data = NULL;
avPacket.size = 0;
fflush(stdout);
success = avcodec_encode_video2( m_pCodecContext, &avPacket, NULL, &result );
if( result )
{
success = processFrame( avPacket );
}
av_packet_unref( &avPacket );
if (!result)
{
break;
}
}
}
if (m_pFormatContext)
{
av_write_trailer( m_pFormatContext );
if( m_pFrame )
{
av_frame_free( &m_pFrame );
}
avio_closep( &m_pFormatContext->pb );
avformat_free_context( m_pFormatContext );
m_pFormatContext = NULL;
}
}
void cleanup()
{
if( m_pFrame || m_pCodecContext )
{
if( m_pFrame )
{
av_frame_free( &m_pFrame );
}
if( m_pCodecContext )
{
avcodec_close( m_pCodecContext );
av_free( m_pCodecContext );
}
}
}
int main()
{
bool success = true;
if (initialize())
{
if (startExport())
{
for (int loop = 0; loop < m_frameCount; loop++)
{
if (!exportFrame())
{
std::cout << "Failed to export frame\n";
success = false;
break;
}
}
endExport();
}
else
{
std::cout << "Failed to start export\n";
success = false;
}
cleanup();
}
else
{
std::cout << "Failed to initialize export\n";
success = false;
}
if (success)
{
std::cout << "Successfully exported file\n";
}
return 1;
}
The problem no longer occurs now that I have updated to the latest Intel® Graphics Driver (version 15.45.10.4542)

CListBox hotlight tracking

I used DrawItem () to redraw CListBox. ods_hotlight does not work in win7/win8.
How can I do this CListBox hotlight tracking?
OK ,I solved this now .... ,Code posted below :
extern "C" WINUSERAPI BOOL WINAPI TrackMouseEvent (LPTRACKMOUSEEVENT lpEventTrack);
void CListBoxCS::OnMouseMove(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof(TRACKMOUSEEVENT);
tme.dwFlags = TME_HOVER | TME_LEAVE;
tme.dwHoverTime = HOVER_DEFAULT;
tme.hwndTrack = m_hWnd;
tme.dwHoverTime = 1;
TrackMouseEvent (&tme);
BOOL bOut = TRUE;
short index;
index = (short) ItemFromPoint (point,bOut);
if (FALSE == bOut) {
if (m_ihot != index) {
m_ihot = index;
//printf ("index = %d \n",m_ihot);
Invalidate (FALSE);
}
} else {
//printf ( "out \n" );
}
}
void CListBoxCS::OnMouseLeave (void)
{
//printf ( "mouse leave \n" );
m_ihot = -1;
}
void CListBoxCS::DrawItem (LPDRAWITEMSTRUCT lpDrawItemStruct)
{
// some judgements here .....
// some preparations
// hot light code ...
if ((act & ODA_SELECT) || (act & ODA_DRAWENTIRE)) {
if (lpDIS->itemState & ODS_SELECTED) {
dc.FillSolidRect (&lpDIS->rcItem,(RGB (209, 232, 255)));
} else {
dc.FillSolidRect (&lpDIS->rcItem,(RGB (230, 230, 230)));
}
if (m_ihot == lpDrawItemStruct->itemID) {
dc.FillSolidRect (&lpDIS->rcItem,(RGB (229, 243, 251)));
}
}
// something U like to do ....
}

Resources