text section of MFC in memory changes everytime - visual-c++

I am trying to implement self integrity check in MFC exe.
Ref : -
Tamper Aware and Self Healing Code : Codeproject
I dumped text section
ofstream myfile;
myfile.open ("textsec.bin");
myfile.write((const char*)pCodeStart,dwCodeSize);
myfile.close();
every time its different so hash for it is also different. Please Help
I want to check text i.e. code section in memory should be same as that in file present on disk.
So we can be sure that our exe file in memory is not patched.
we can use while distributing product exe.
We will get start of code section in memory by
VOID ImageInformation( HMODULE& hModule, PVOID& pVirtualAddress,
PVOID& pCodeStart, SIZE_T& dwCodeSize,
PVOID& pCodeEnd )
{
const UINT PATH_SIZE = 2 * MAX_PATH;
TCHAR szFilename[ PATH_SIZE ] = { 0 };
__try {
/////////////////////////////////////////////////
/////////////////////////////////////////////////
if( 0 == GetModuleFileName( NULL, szFilename, PATH_SIZE ) )
{
std::tcerr << _T("Error Retrieving Process Filename");
std::tcerr << std::endl;
__leave;
}
hModule = GetModuleHandle( szFilename );
if( NULL == hModule )
{
std::tcerr << _T("Error Retrieving Process Module Handle");
std::tcerr << std::endl;
__leave;
}
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
PIMAGE_DOS_HEADER pDOSHeader = NULL;
pDOSHeader = static_cast<PIMAGE_DOS_HEADER>( (PVOID)hModule );
if( pDOSHeader->e_magic != IMAGE_DOS_SIGNATURE )
{
std::tcerr << _T("Error - File is not EXE Format");
std::tcerr << std::endl;
__leave;
}
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
PIMAGE_NT_HEADERS pNTHeader = NULL;
pNTHeader = reinterpret_cast<PIMAGE_NT_HEADERS>(
(PBYTE)hModule + pDOSHeader->e_lfanew );
if( pNTHeader->Signature != IMAGE_NT_SIGNATURE )
{
std::tcerr << _T("Error - File is not PE Format") << std::endl;
__leave;
}
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
PIMAGE_FILE_HEADER pFileHeader = NULL;
pFileHeader = reinterpret_cast<PIMAGE_FILE_HEADER>(
(PBYTE)&pNTHeader->FileHeader );
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
PIMAGE_OPTIONAL_HEADER pOptionalHeader = NULL;
pOptionalHeader = reinterpret_cast<PIMAGE_OPTIONAL_HEADER>(
(PBYTE)&pNTHeader->OptionalHeader );
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
if( IMAGE_NT_OPTIONAL_HDR32_MAGIC !=
pNTHeader->OptionalHeader.Magic )
{
std::tcerr << _T("Error - File is not 32 bit") << std::endl;
__leave;
}
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
PIMAGE_SECTION_HEADER pSectionHeader = NULL;
pSectionHeader = reinterpret_cast<PIMAGE_SECTION_HEADER>(
(PBYTE)&pNTHeader->OptionalHeader +
pNTHeader->FileHeader.SizeOfOptionalHeader );
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
const CHAR TEXT[] = ".text";
const CHAR BSSTEXT[] = ".textbss";
UINT nSectionCount = pNTHeader->FileHeader.NumberOfSections;
CHAR szSectionName[ IMAGE_SIZEOF_SHORT_NAME + 1 ];
szSectionName[ IMAGE_SIZEOF_SHORT_NAME ] = '\0';
for( UINT i = 0; i < nSectionCount; i++ )
{
memcpy( szSectionName, pSectionHeader->Name,
IMAGE_SIZEOF_SHORT_NAME );
if( 0 == strncmp( TEXT, szSectionName,
IMAGE_SIZEOF_SHORT_NAME ) )
{
std::tcout << std::endl;
break;
}
pSectionHeader++;
}
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
if( 0 != strncmp( TEXT, szSectionName, IMAGE_SIZEOF_SHORT_NAME ) )
{
std::tcerr << _T("Error - Unable to locate ");
std::cerr << TEXT;
std::tcerr << _T(" TEXT") << std::endl;
__leave;
}
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
pVirtualAddress = (PVOID)(pSectionHeader->VirtualAddress);
dwCodeSize = pSectionHeader->Misc.VirtualSize;
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
pCodeStart = (PVOID)(((PBYTE)hModule) +
(SIZE_T)((PBYTE)pVirtualAddress) );
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
pCodeEnd = (PVOID)((PBYTE)pCodeStart + dwCodeSize );
}
__except( EXCEPTION_EXECUTE_HANDLER ) {
std::tcerr << std::endl << _T("Caught Exception") << std::endl;
}
}
Now we can calculate hash of code section
CalculateImageHash( pCodeStart, dwCodeSize, cbCalculatedImageHash );
then we compare with cbExpectedImageHash. cbExpectedImageHash is predefined global
if( 0 == memcmp( cbExpectedImageHash, cbCalculatedImageHash,
CryptoPP::SHA224::DIGESTSIZE ) )
{
std::tcout << _T("Image is verified.") << std::endl;
}
In MFC cbCalculatedImageHash is every time different . :( but not in console app.
cbExpectedImageHash and cbCalculatedImageHash are globel .
here is full code of my dialog
// UserAppDlg.cpp : implementation file
//
#include "stdafx.h"
#include "UserApp.h"
#include "UserAppDlg.h"
#include "sha.h" // SHA
#include "hex.h" // HexEncoder
#include "files.h" // FileSink
#include "filters.h" // StringSink
#include "gzip.h"
using namespace std;
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CAboutDlg dialog used for App About
// we can add cbExpectedImageHash new values if we get calcualted hash same every
BYTE cbExpectedImageHash[ CryptoPP::SHA224::DIGESTSIZE ] =
{
0xBA, 0x71, 0x29, 0xD8, 0x79, 0x4E, 0xA3, 0x5A, 0x2C, 0xE0
, 0xC5, 0x3A, 0x68, 0x9E, 0xE8, 0x29, 0x09, 0x44, 0xFA, 0x71
, 0xAF, 0xDB,0x3E,0x88,0xAD,0x65,0x67,0x78
};
BYTE cbCalculatedImageHash[ CryptoPP::SHA224::DIGESTSIZE ] ;
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// CUserAppDlg dialog
CUserAppDlg::CUserAppDlg(CWnd* pParent /*=NULL*/)
: CDialog(CUserAppDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CUserAppDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CUserAppDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
// CUserAppDlg message handlers
int CUserAppDlg::ImageInformation( HMODULE& hModule, PVOID& pVirtualAddress,
PVOID& pCodeStart, SIZE_T& dwCodeSize,
PVOID& pCodeEnd )
{
const UINT PATH_SIZE = 2 * MAX_PATH;
TCHAR szFilename[ PATH_SIZE ] = { 0 };
__try {
/////////////////////////////////////////////////
/////////////////////////////////////////////////
if( 0 == GetModuleFileName( NULL, szFilename, PATH_SIZE ) )
{
// std::tcerr << _T("Error Retrieving Process Filename");
// std::tcerr << std::endl;
__leave;
}
hModule = GetModuleHandle( szFilename );
if( NULL == hModule )
{
// std::tcerr << _T("Error Retrieving Process Module Handle");
// std::tcerr << std::endl;
__leave;
}
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
PIMAGE_DOS_HEADER pDOSHeader = NULL;
pDOSHeader = static_cast<PIMAGE_DOS_HEADER>( (PVOID)hModule );
if( pDOSHeader->e_magic != IMAGE_DOS_SIGNATURE )
{
// std::tcerr << _T("Error - File is not EXE Format");
// std::tcerr << std::endl;
__leave;
}
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
PIMAGE_NT_HEADERS pNTHeader = NULL;
pNTHeader = reinterpret_cast<PIMAGE_NT_HEADERS>(
(PBYTE)hModule + pDOSHeader->e_lfanew );
if( pNTHeader->Signature != IMAGE_NT_SIGNATURE )
{
// std::tcerr << _T("Error - File is not PE Format") << std::endl;
__leave;
}
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
PIMAGE_FILE_HEADER pFileHeader = NULL;
pFileHeader = reinterpret_cast<PIMAGE_FILE_HEADER>(
(PBYTE)&pNTHeader->FileHeader );
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
PIMAGE_OPTIONAL_HEADER pOptionalHeader = NULL;
pOptionalHeader = reinterpret_cast<PIMAGE_OPTIONAL_HEADER>(
(PBYTE)&pNTHeader->OptionalHeader );
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
if( IMAGE_NT_OPTIONAL_HDR32_MAGIC !=
pNTHeader->OptionalHeader.Magic )
{
// std::tcerr << _T("Error - File is not 32 bit") << std::endl;
__leave;
}
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
PIMAGE_SECTION_HEADER pSectionHeader = NULL;
pSectionHeader = reinterpret_cast<PIMAGE_SECTION_HEADER>(
(PBYTE)&pNTHeader->OptionalHeader +
pNTHeader->FileHeader.SizeOfOptionalHeader );
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
const CHAR TEXT[] = ".text";
const CHAR BSSTEXT[] = ".textbss";
UINT nSectionCount = pNTHeader->FileHeader.NumberOfSections;
CHAR szSectionName[ IMAGE_SIZEOF_SHORT_NAME + 1 ];
szSectionName[ IMAGE_SIZEOF_SHORT_NAME ] = '\0';
for( UINT i = 0; i < nSectionCount; i++ )
{
memcpy( szSectionName, pSectionHeader->Name,
IMAGE_SIZEOF_SHORT_NAME );
if( 0 == strncmp( TEXT, szSectionName,
IMAGE_SIZEOF_SHORT_NAME ) )
{
// std::tcout << std::endl;
break;
}
pSectionHeader++;
}
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
if( 0 != strncmp( TEXT, szSectionName, IMAGE_SIZEOF_SHORT_NAME ) )
{
// std::tcerr << _T("Error - Unable to locate ");
// std::cerr << TEXT;
// std::tcerr << _T(" TEXT") << std::endl;
__leave;
}
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
pVirtualAddress = (PVOID)(pSectionHeader->VirtualAddress);
dwCodeSize = pSectionHeader->Misc.VirtualSize;
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
pCodeStart = (PVOID)(((PBYTE)hModule) +
(SIZE_T)((PBYTE)pVirtualAddress) );
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
pCodeEnd = (PVOID)((PBYTE)pCodeStart + dwCodeSize );
}
__except( EXCEPTION_EXECUTE_HANDLER ) {
// std::tcerr << std::endl << _T("Caught Exception") << std::endl;
}
return 0;
}
void CUserAppDlg::CalculateImageHash( PVOID pCodeStart, SIZE_T dwCodeSize,
PBYTE pcbDigest )
{
CryptoPP::SHA224 hash;
hash.Update( (PBYTE)pCodeStart, dwCodeSize );
hash.Final( pcbDigest );
}
BOOL CUserAppDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
HMODULE hModule = NULL;
PVOID pVirtualAddress = NULL;
PVOID pCodeStart = NULL;
PVOID pCodeEnd = NULL;
SIZE_T dwCodeSize = 0;
ImageInformation( hModule, pVirtualAddress, pCodeStart,
dwCodeSize, pCodeEnd );
ofstream myfile;
myfile.open ("textsec.bin"); //textsec.bin changes everytime
myfile.write((const char*)pCodeStart,dwCodeSize);
myfile.close();
CalculateImageHash( pCodeStart, dwCodeSize, cbCalculatedImageHash ); //cbCalculatedImageHash changes everytime
myfile.open ("CalculateImageHash.bin");
myfile.write((const char*)cbCalculatedImageHash,CryptoPP::SHA224::DIGESTSIZE);
myfile.close();
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
return TRUE; // return TRUE unless you set the focus to a control
}
void CUserAppDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CUserAppDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CUserAppDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}

Related

getting response only on the first time with socket programming

I'm trying to create an HTTP server using C++ 98.
The issue is that, every time I launch my server, I get the response, sending again the request from the same browser tab, and the browser keeps loading.
In my kqueue, it seems like the block for checking the read event is not being executed on the second time.
This is my code:
void webserv::Server::lunch(){
this->kq.create_event(this->sock.getSocket(), EVFILT_READ);
while(1)
this->_lunch_worker();
}
void webserv::Server::_lunch_worker(void)
{
int n_ev;
int accept_sock;
int address_size;
char buff[1000];
webserv::Header header;
// register the events in ev_list
std::cout << GREEN << "---- WAITING FOR CONNECTION ----" << RESET << std::endl;
n_ev = this->kq.get_event();
for (int i = 0; i < n_ev; i++)
{
if (this->kq.get_fd(i) < 0)
continue;
if (this->kq.get_fd(i) == this->sock.getSocket())
{
std::cout << "--- RECEIVED NEW CONNECTION ---" << std::endl;
address_size = sizeof(this->sock.getAddress());
accept_sock = accept(
this->sock.getSocket(),
(struct sockaddr*)&this->sock.getAddress(),
(socklen_t *)&address_size
);
this->sock.test_error(accept_sock);
this->kq.create_event(accept_sock, EVFILT_READ);
int flags;
if ((flags = fcntl(accept_sock, F_GETFL, 0)) < 0) {
perror("fcntl");
close(accept_sock);
close(this->sock.getSocket());
}
if (fcntl(accept_sock, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("fcntl");
close(accept_sock);
close(this->sock.getSocket());
}
this->kq.create_event(accept_sock, EVFILT_WRITE, EV_ADD | EV_ONESHOT);
}
else if (this->kq.is_read_available(i))
{
int bytes_read;
std::cout << "START: is_read_available" << std::endl;
if ((bytes_read = recv(this->kq.get_fd(i), buff, 999, 0)) > 0)
{
}
}
else if (this->kq.is_write_available(i))
{
std::string hello = "HTTP/1.1 200 OK\nContent-Type: text/plain\nContent-Length: 12\n\nHello world!";
if (send(this->kq.get_fd(i), hello.c_str(), hello.length(), 0) != 0)
{
std::cout << "TEST2" << std::endl;
this->kq.set_event(this->kq.get_fd(i), EVFILT_WRITE, EV_DELETE);
this->kq.get_event_list()[i].ident = -1;
close(this->kq.get_fd(i));
}
std::cout << "END: is_write_available" << std::endl;
}
}
}
And this is the kqueue class:
/************************ CONSTRUCTORS/DESTRUCTOR ************************/
webserv::Kqueue::Kqueue()
{
this->_kq = kqueue();
std::cout << "KQUEUE CREATED" << std::endl;
this->test_error(this->_kq, "Creating Kqueue :");
this->_n_ev = 0;
}
webserv::Kqueue::~Kqueue()
{
close(this->_kq);
}
/************************ MEMBER FUNCTIONS ************************/
void webserv::Kqueue::set_event(int fd, int filter, int flags, void *udata)
{
EV_SET(&this->_ev_set, fd, filter, flags, 0, 0, udata);
}
void webserv::Kqueue::add_event(void)
{
int ret;
ret = kevent(this->_kq, &this->_ev_set, 1, NULL, 0, NULL);
this->test_error(ret, "Kqueue/add_even functions");
}
int webserv::Kqueue::get_event(void)
{
this->_n_ev = kevent(this->_kq, NULL, 0, this->_ev_list, __EV_LIST_SIZE__, NULL);
this->test_error(this->_n_ev, "Kqueue/get_event function:");
return (this->_n_ev);
}
void webserv::Kqueue::create_event(int fd, int filter, int flags, void *udata)
{
this->set_event(fd, filter, flags, udata);
this->add_event();
}
bool webserv::Kqueue::isEOF(int index)
{
if (this->_n_ev <= index)
this->test_error(-1, "Kqueue/isEOF function:");
return (this->_ev_list[index].flags & EV_EOF);
}
bool webserv::Kqueue::is_read_available(int index)
{
if (this->_n_ev <= index)
this->test_error(-1, "Kqueue/is_read_available function:");
return (this->_ev_list[index].filter == EVFILT_READ);
}
bool webserv::Kqueue::is_write_available(int index)
{
if (this->_n_ev <= index)
this->test_error(-1, "Kqueue/is_write_available function:");
return (this->_ev_list[index].filter == EVFILT_WRITE);
}
void webserv::Kqueue::test_error(int fd, const std::string &str)
{
if (fd < 0)
{
std::cerr << RED << str << " ";
perror("The following error occured: ");
std::cerr << RESET;
exit(EXIT_FAILURE);
}
}
/************************ GETTERS/SETTERS ************************/
struct kevent *webserv::Kqueue::get_event_list()
{
return (this->_ev_list);
}
int webserv::Kqueue::get_fd(int index)
{
if (this->_n_ev <= index)
this->test_error(-1, "Kqueue/get_ev_list function:");
return (this->_ev_list[index].ident);
}
void webserv::Kqueue::set_kqueue(int fd)
{
this->_kq = fd;
}

FFMPEG AAC encoder issue

I am trying to capture and encode audio data, I am encoding audio using
FFMPEG AAC and to capture PCM data I used ALSA, Capturing part is working in my case, However, AAC encoder is not working.
I am trying to play test.aac file using
ffplay test.aac
but it contains lots of noise.
Attaching code for aac encoder :
#include "AudioEncoder.h"
void* AudioEncoder::run(void *ctx)
{
return ((AudioEncoder *)ctx)->execute();
}
static int frameCount = 0;
void* AudioEncoder::execute(void)
{
float buf[size], *temp;
int totalSize = 0;
int fd = open("in.pcm", O_CREAT| O_RDWR, 0666);
int frameSize = 128 * snd_pcm_format_width(SND_PCM_FORMAT_FLOAT) / 8 * 2;
av_new_packet(&pkt,size);
cout << size << endl;
while (!Main::stopThread)
{
temp = (Main::fbAudio)->dequeue();
memcpy(buf + totalSize, temp, frameSize);
write(fd, temp, frameSize); // Can play in.pcm with no noise in it.
totalSize += frameSize;
delete temp;
if (totalSize >= size)
{
totalSize = 0;
//frame_buf = (uint8_t *) buf;
pFrame->data[0] = (uint8_t *)buf; //PCM Data
pFrame->pts=frameCount;
frameCount++;
got_frame=0;
//Encode
ret = avcodec_encode_audio2(pCodecCtx, &pkt,pFrame, &got_frame);
if(ret < 0){
cerr << "Failed to encode!\n";
return NULL;
}
if (got_frame==1){
printf("Succeed to encode 1 frame! \tsize:%5d\n",pkt.size);
pkt.stream_index = audio_st->index;
#ifdef DUMP_TEST
ret = av_write_frame(pFormatCtx, &pkt);
#endif
av_free_packet(&pkt);
}
//memset(buf, 0, sizeof(float)*size);
}
//delete temp;
//if (buf.size() >= m_audio_output_decoder_ctx->frame_size)
/* encode the audio*/
}
close(fd);
Main::stopThread = true;
return NULL;
}
int AudioEncoder::flush_encoder(AVFormatContext *fmt_ctx,unsigned int stream_index){
int ret;
int got_frame;
AVPacket enc_pkt;
if (!(fmt_ctx->streams[stream_index]->codec->codec->capabilities &
CODEC_CAP_DELAY))
return 0;
while (1) {
enc_pkt.data = NULL;
enc_pkt.size = 0;
av_init_packet(&enc_pkt);
ret = avcodec_encode_audio2 (fmt_ctx->streams[stream_index]->codec, &enc_pkt,
NULL, &got_frame);
av_frame_free(NULL);
if (ret < 0)
break;
if (!got_frame){
ret=0;
break;
}
printf("Flush Encoder: Succeed to encode 1 frame!\tsize:%5d\n",enc_pkt.size);
/* mux encoded frame */
#ifdef DUMP_TEST
ret = av_write_frame(fmt_ctx, &enc_pkt);
if (ret < 0)
break;
#endif
}
return ret;
}
void AudioEncoder::start(void)
{
pthread_t encoder;
pthread_create(&encoder, NULL, &AudioEncoder::run, this);
}
AudioEncoder::AudioEncoder() : out_file("test.aac")
{
got_frame = 0;
ret = 0;
size = 0;
av_register_all();
avcodec_register_all();
//Method 1.
pFormatCtx = avformat_alloc_context();
fmt = av_guess_format(NULL, out_file, NULL);
pFormatCtx->oformat = fmt;
#ifdef DUMP_TEST
if (avio_open(&pFormatCtx->pb,out_file, AVIO_FLAG_READ_WRITE) < 0){
cerr << "Failed to open output file!\n";
return;
}
#endif
audio_st = avformat_new_stream(pFormatCtx, 0);
if (audio_st==NULL){
return;
}
pCodecCtx = audio_st->codec;
pCodecCtx->codec_id = fmt->audio_codec;
pCodecCtx->codec_type = AVMEDIA_TYPE_AUDIO;
pCodecCtx->sample_fmt = AV_SAMPLE_FMT_FLTP;
pCodecCtx->sample_rate= 8000;
pCodecCtx->channel_layout=AV_CH_LAYOUT_STEREO;
pCodecCtx->channels = av_get_channel_layout_nb_channels(pCodecCtx->channel_layout);
// pCodecCtx->bit_rate = 64000;
#ifdef DUMP_TEST
//Show some information
av_dump_format(pFormatCtx, 0, out_file, 1);
#endif
pCodec = avcodec_find_encoder(pCodecCtx->codec_id);
if (!pCodec){
printf("Can not find encoder!\n");
return;
}
if (avcodec_open2(pCodecCtx, pCodec,NULL) < 0){
printf("Failed to open encoder!\n");
return;
}
pFrame = av_frame_alloc();
pFrame->nb_samples= pCodecCtx->frame_size;
pFrame->format= pCodecCtx->sample_fmt;
size = av_samples_get_buffer_size(NULL, pCodecCtx->channels,pCodecCtx->frame_size,pCodecCtx->sample_fmt, 1);
frame_buf = (uint8_t *)av_malloc(size);
avcodec_fill_audio_frame(pFrame, pCodecCtx->channels, pCodecCtx->sample_fmt,(const uint8_t*)frame_buf, size, 1);
//Write Header
#ifdef DUMP_TEST
avformat_write_header(pFormatCtx,NULL);
#endif
}
AudioEncoder::~AudioEncoder()
{
//Flush Encoder
ret = flush_encoder(pFormatCtx,0);
if (ret < 0) {
cerr << "Flushing encoder failed\n";
return;
}
#ifdef DUMP_TEST
//Write Trailer
av_write_trailer(pFormatCtx);
#endif
//Clean
if (audio_st){
avcodec_close(audio_st->codec);
av_free(pFrame);
av_free(frame_buf);
}
avio_close(pFormatCtx->pb);
avformat_free_context(pFormatCtx);
}
Here, please ignore DUMP_TEST flag, I already enabled it.
Can some one tell me what is issue ?
Thanks,
Harshil
I am able to resolve this issue, by correctly passing buffer from ALSA to AAC encoder.
Here AAC expects buffer size of 4096 bytes, but from deque I am passing 1024 bytes which causes issue, also I updated audio channels to MONO, in place of STEREO. Attaching my working code snippet for more information:
#include "AudioEncoder.h"
void* AudioEncoder::run(void *ctx)
{
return ((AudioEncoder *)ctx)->execute();
}
static int frameCount = 0;
void* AudioEncoder::execute(void)
{
float *temp;
#ifdef DUMP_TEST
int fd = open("in.pcm", O_CREAT| O_RDWR, 0666);
#endif
int frameSize = 1024 * snd_pcm_format_width(SND_PCM_FORMAT_FLOAT) / 8 * 1;
av_new_packet(&pkt,size);
while (!Main::stopThread)
{
temp = (Main::fbAudio)->dequeue();
frame_buf = (uint8_t *) temp;
pFrame->data[0] = frame_buf;
pFrame->pts=frameCount*100;
frameCount++;
got_frame=0;
//Encode
ret = avcodec_encode_audio2(pCodecCtx, &pkt,pFrame, &got_frame);
if(ret < 0){
cerr << "Failed to encode!\n";
return NULL;
}
if (got_frame==1){
cout << "Encoded frame\n";
pkt.stream_index = audio_st->index;
#ifdef DUMP_TEST
write(fd, temp, frameSize);
ret = av_interleaved_write_frame(pFormatCtx, &pkt);
#endif
av_free_packet(&pkt);
}
delete temp;
}
#ifdef DUMP_TEST
close(fd);
#endif
Main::stopThread = true;
return NULL;
}
int AudioEncoder::flush_encoder(AVFormatContext *fmt_ctx,unsigned int stream_index){
int ret;
int got_frame;
AVPacket enc_pkt;
if (!(fmt_ctx->streams[stream_index]->codec->codec->capabilities &
CODEC_CAP_DELAY))
return 0;
while (1) {
enc_pkt.data = NULL;
enc_pkt.size = 0;
av_init_packet(&enc_pkt);
ret = avcodec_encode_audio2 (fmt_ctx->streams[stream_index]->codec, &enc_pkt,
NULL, &got_frame);
av_frame_free(NULL);
if (ret < 0)
break;
if (!got_frame){
ret=0;
break;
}
printf("Flush Encoder: Succeed to encode 1 frame!\tsize:%5d\n",enc_pkt.size);
/* mux encoded frame */
#ifdef DUMP_TEST
ret = av_write_frame(fmt_ctx, &enc_pkt);
if (ret < 0)
break;
#endif
}
return ret;
}
void AudioEncoder::start(void)
{
pthread_t encoder;
pthread_create(&encoder, NULL, &AudioEncoder::run, this);
}
AudioEncoder::AudioEncoder() : out_file("test.aac")
{
got_frame = 0;
ret = 0;
size = 0;
av_register_all();
avcodec_register_all();
//Method 1.
pFormatCtx = avformat_alloc_context();
fmt = av_guess_format(NULL, out_file, NULL);
pFormatCtx->oformat = fmt;
#ifdef DUMP_TEST
if (avio_open(&pFormatCtx->pb,out_file, AVIO_FLAG_READ_WRITE) < 0){
cerr << "Failed to open output file!\n";
return;
}
#endif
audio_st = avformat_new_stream(pFormatCtx, 0);
if (audio_st==NULL){
return;
}
pCodecCtx = audio_st->codec;
pCodecCtx->codec_id = fmt->audio_codec;
pCodecCtx->codec_type = AVMEDIA_TYPE_AUDIO;
pCodecCtx->sample_fmt = AV_SAMPLE_FMT_FLTP;
pCodecCtx->sample_rate= 8000;
pCodecCtx->channel_layout=AV_CH_LAYOUT_MONO;
pCodecCtx->channels = av_get_channel_layout_nb_channels(pCodecCtx->channel_layout);
pCodecCtx->bit_rate = 64000;
#ifdef DUMP_TEST
//Show some information
av_dump_format(pFormatCtx, 0, out_file, 1);
#endif
pCodec = avcodec_find_encoder(pCodecCtx->codec_id);
if (!pCodec){
printf("Can not find encoder!\n");
return;
}
if (avcodec_open2(pCodecCtx, pCodec,NULL) < 0){
printf("Failed to open encoder!\n");
return;
}
pFrame = av_frame_alloc();
pFrame->nb_samples= pCodecCtx->frame_size;
pFrame->format= pCodecCtx->sample_fmt;
size = av_samples_get_buffer_size(NULL, pCodecCtx->channels,pCodecCtx->frame_size,pCodecCtx->sample_fmt, 1);
frame_buf = (uint8_t *)av_malloc(size);
avcodec_fill_audio_frame(pFrame, pCodecCtx->channels, pCodecCtx->sample_fmt,(const uint8_t*)frame_buf, size, 1);
//Write Header
#ifdef DUMP_TEST
avformat_write_header(pFormatCtx,NULL);
#endif
}
AudioEncoder::~AudioEncoder()
{
//Flush Encoder
ret = flush_encoder(pFormatCtx,0);
if (ret < 0) {
cerr << "Flushing encoder failed\n";
return;
}
#ifdef DUMP_TEST
//Write Trailer
av_write_trailer(pFormatCtx);
#endif
//Clean
if (audio_st){
avcodec_close(audio_st->codec);
av_free(pFrame);
av_free(frame_buf);
}
avio_close(pFormatCtx->pb);
avformat_free_context(pFormatCtx);
}

SDL2/GL context defaults to v3.0 on linux mint

When I compile & run my code to create an opengl 3.3 or above context (identical to the windows version, with one or two extra lines), it defaults to 3.0, which will cause problems with some of my applications I want to port over.
I'm looking for a fix/explanation of this.
Source as follows:
//Using SDL and standard IO
#include <SDL2/SDL.h>
#include <stdio.h>
#include <GL/glew.h>
//Screen dimension constants
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
bool handleEvent(SDL_Event& event)
{
return true;
}
int main( int argc, char* args[] )
{
//The window we'll be rendering to
SDL_Window* window = NULL;
//Initialize SDL
if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
{
printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
}
else
{
//Create window
window = SDL_CreateWindow("SDL/GLM/OpenGL Demo", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN );
if( window == NULL )
{
printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
}
else
{
SDL_GLContext context = SDL_GL_CreateContext(window);
SDL_GL_MakeCurrent(window, context);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetSwapInterval(1); // set swap buffers to sync with monitor's vertical refresh rate
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glewExperimental = GL_TRUE;
glClearColor(1.0,0.0,0.0,1.0);
GLenum err = glewInit();
if (err != GLEW_OK)
{
printf("glew init failed: %s!\n", glewGetErrorString(err));
}
printf("opengl version :%s\n",glGetString(GL_VERSION));
bool running = true; // set running to true
SDL_Event sdlEvent; // variable to detect SDL events
while (running)
{ // the event loop
while (SDL_PollEvent(&sdlEvent))
{
if (sdlEvent.type == SDL_QUIT)
running = false;
else
{
running = handleEvent(sdlEvent);
}
}
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
SDL_GL_SwapWindow(window);
}
SDL_GL_DeleteContext(context);
SDL_DestroyWindow(window);
}
}
SDL_Quit();
return 0;
}
You need to set GL attributes before you create a window, not after you create a context:
SDL_GL_SetAttribute()
Use this function to set an OpenGL window attribute before window creation.
Example:
#include <GL/glew.h>
#include <SDL2/SDL.h>
#include <iostream>
int main( int argc, char** argv )
{
SDL_Init( SDL_INIT_EVERYTHING );
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_Window* window = SDL_CreateWindow
(
"SDL2",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
300, 300,
SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL
);
if( NULL == window )
{
std::cerr << "Failed to create window: " << SDL_GetError() << std::endl;
SDL_Quit();
return 0;
}
SDL_GLContext context = SDL_GL_CreateContext(window);
if( NULL == context )
{
std::cerr << "Failed to create GL context: " << SDL_GetError() << std::endl;
SDL_DestroyWindow( window );
SDL_Quit();
return -1;
}
if( SDL_GL_MakeCurrent( window, context ) < 0 )
{
std::cerr << "Failed to make GL context current: " << SDL_GetError() << std::endl;
SDL_GL_DeleteContext( context );
SDL_DestroyWindow( window );
SDL_Quit();
return -1;
}
std::cout << "GL_VERSION: " << glGetString( GL_VERSION ) << std::endl;
SDL_GL_SetSwapInterval(1);
glewExperimental = GL_TRUE;
GLenum err = glewInit();
if( GLEW_OK != err )
{
std::cerr << "Failed init GLEW: " << glewGetErrorString( err ) << std::endl;
SDL_GL_DeleteContext( context );
SDL_DestroyWindow( window );
SDL_Quit();
return -1;
}
bool running = true;
while( running )
{
SDL_Event ev;
while( SDL_PollEvent( &ev ) )
{
if ( ev.type == SDL_QUIT )
running = false;
}
glClear( GL_COLOR_BUFFER_BIT );
SDL_GL_SwapWindow( window );
}
SDL_GL_DeleteContext( context );
SDL_DestroyWindow( window );
SDL_Quit();
return 0;
}
As it turns out, mesa drivers do not support OpenGL contexts above 3.0, so the driver will default to the maximum available, which is 3.0. In order to create a 3.x context, you must have proprietary drivers installed. Once I had installed those drivers everything worked fine.

socket() returning file descriptor 1 inside std::thread

When I call socket() inside a std::thread() it returns a socket descriptor of 1. Calls to std::cout than send the text meant for the terminal to the server. When I added cout << ""; prior to the call to socket(), descriptors for stdin/out/err for are created and socket() returns 3.
From http://www.cplusplus.com/reference/iostream/cout/:
In terms of static initialization order, cout is guaranteed to be properly constructed and initialized no later than the first time an object of type ios_base::Init is constructed, with the inclusion of <iostream> counting as at least one initialization of such objects with static duration.
By default, cout is synchronized with stdout (see ios_base::sync_with_stdio).
std::cout should already be initialized and synchronized to stdout which explains why std::cout is sending the message to the server and not the terminal.
I'm wondering if calling std::thread() closes the stdin/out/err descriptors in the new thread or if these descriptors don't exist in the thread since the thread wasn't created by the terminal or initd?
I'm running on RHEL 6.4 using GCC 4.8.2. I've included my client code below with the additional cout << ""; commented out for completeness.
Client.cpp:
#include "Client.hpp"
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <thread>
#include <vector>
#include <algorithm>
#include <sstream>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
using namespace std;
Client::Client( const string& hostname, const string& port ) {
this->hostname = hostname;
this->port = port;
}
Client::~Client() { close( fd ); }
void Client::operator()() {
struct addrinfo hints;
memset( &hints, 0, sizeof( struct addrinfo ) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = 0;
hints.ai_protocol = 0;
struct addrinfo *result;
int ret = getaddrinfo( hostname.c_str(), port.c_str(), &hints, &result );
if( ret != 0) {
cerr << "getaddrinfo failed: " << gai_strerror( ret ) << endl;
return;
}
// cout << ""; // prevents socket() from returning 1 and redefining cout
struct addrinfo *rp = NULL;
for( rp = result; rp != NULL; rp = rp->ai_next ) {
fd = socket( rp->ai_family, rp->ai_socktype, rp->ai_protocol );
if( fd == -1 ) {
continue; /* Error */
}
if( connect( fd, rp->ai_addr, rp->ai_addrlen ) != -1) {
break; /* Success */
}
close( fd ); /* Try again */
}
if( rp == NULL ) {
cerr << "Failed to connect to " << hostname << ":" << port << endl;
return;
}
freeaddrinfo( result );
cout << "Starting echo client" << endl;
int i = 0;
do {
stringstream ss;
ss << "Thread " << this_thread::get_id() << ": Message #" << ++i;
string str = ss.str();
_send( str.c_str() );
string msg = _recv();
//cout << "Thread " << this_thread::get_id() << " received message: " << msg << endl;
} while ( i < 10 );
cout << "Stopping echo client" << endl;
close( fd );
}
string Client::_recv( ) const {
const int BUF_SIZE = 1024;
char* buf = ( char * ) malloc( sizeof( char) * BUF_SIZE );
memset( buf, '\0', sizeof( char ) * BUF_SIZE );
int bytes = recv( fd, buf, BUF_SIZE, 0 );
if( bytes < 0 ) {
perror( "recv failed" );
}
string msg = string( buf );
free( buf );
return msg;
}
void Client::_send( const string buf ) const {
if( send( fd, buf.c_str(), buf.length(), 0 ) < 0 ) {
perror( "send failed" );
}
}
void usage() {
cerr << "Usage: client <hostname> <port>" << endl;
cerr << " hostname - server name listening for incoming connctions" << endl;
cerr << " port - internet port to listen for connections from" << endl;
}
int main( int argc, char* argv[] ) {
if( argc < 3 ) {
cerr << "Not enough arguments!" << endl;
usage();
return EXIT_FAILURE;
}
vector<thread> clients;
for( int i = 0; i < 1; i++ ) {
clients.push_back( thread( ( Client( argv[1], argv[2] ) ) ) );
}
for_each( clients.begin(), clients.end(), mem_fn( &thread::join ) );
return EXIT_SUCCESS;
}
Client.hpp:
#ifndef __CLIENT_HPP__
#define __CLIENT_HPP__
#include <string>
class Client {
private:
int fd;
std::string hostname;
std::string port;
std::string _recv( ) const;
void _send( const std::string buf ) const;
public:
Client( const std::string& hostname, const std::string& port);
~Client();
void operator()();
};
#endif
This normally happens if you accidentally close your stdout, i.e. there is a spurious close(1);. Then the FD will legitimately be number 1. This may well be elsewhere in the program.
I've had this several times, and normally find it with gdb and setting a breakpoint on close().
Your destructor looks suspicious:
Client::~Client() { close( fd ); }
Shouldn't you be setting fd to -1 in the constructor, and carefully setting fd to -1 wherever else you close it, and not doing this close if fd==-1? Currently creating a Client and destroying it will close a random fd.

How to prepare eclipse for opencl programming (Intel OpenCL SDK Installed) in Linux

I installed Intel OpenCL SDK on OpenSUSE GNU/Linux 13.1. How do I prepare the Eclipse CDT IDE that comes with my distribution for OpenCL programming?
Edit:
After adding include path /opt/intel/opencl-xxx/inlcude to project and linking /opt/intel/opencl-xxx/lib64/libOpenCL.so to /usr/lib64/libOpenCL.so, Eclipse will find the CL/cl.h but GCC return this error:
Building file: ../src/HelloWorld.cpp
Invoking: GCC C++ Compiler
g++ -I/opt/intel/opencl-1.2-3.2.1.16712/include/ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/HelloWorld.d" -MT"src/HelloWorld.d" -o "src/HelloWorld.o" "../src/HelloWorld.cpp"
../src/HelloWorld.cpp:11:16: fatal error: cl.h: No such file or directory
#include <cl.h>
^
compilation terminated.
make: *** [src/HelloWorld.o] Error 1
Edit 2:
HelloWorld.cpp :
#include <iostream>
#include <fstream>
#include <sstream>
#include <CL\cl.h>
const int ARRAY_SIZE = 1000;
cl_context CreateContext() {
cl_int errNum;
cl_uint numPlatforms;
cl_platform_id firstPlatformId;
cl_context context = NULL;
errNum = clGetPlatformIDs(1, &firstPlatformId, &numPlatforms);
if (errNum != CL_SUCCESS || numPlatforms <= 0) {
std::cerr << "Failed to find any OpenCL platforms." << std::endl;
return NULL;
}
cl_context_properties contextProperties[] = {
CL_CONTEXT_PLATFORM,
(cl_context_properties)firstPlatformId,
0
};
context = clCreateContextFromType(contextProperties, CL_DEVICE_TYPE_GPU,
NULL, NULL, &errNum);
if (errNum != CL_SUCCESS) {
std::cout << "Could not create GPU context, trying CPU..." << std::endl;
context = clCreateContextFromType(contextProperties, CL_DEVICE_TYPE_CPU, NULL, NULL, &errNum);
if (errNum != CL_SUCCESS) {
std::cerr << "Failed to create an OpenCL GPU or CPU context." << std::endl;
return NULL;
}
}
return context;
}
cl_command_queue CreateCommandQueue(cl_context context, cl_device_id *device)
{
cl_int errNum;
cl_device_id *devices;
cl_command_queue commandQueue = NULL;
size_t deviceBufferSize = -1;
errNum = clGetContextInfo(context, CL_CONTEXT_DEVICES, 0, NULL, &deviceBufferSize);
if (errNum != CL_SUCCESS) {
std::cerr << "Failed call to clGetContextInfo(...,GL_CONTEXT_DEVICES,...)";
return NULL;
}
if (deviceBufferSize <= 0) {
std::cerr << "No devices available.";
return NULL;
}
devices = new cl_device_id[deviceBufferSize / sizeof(cl_device_id)];
errNum = clGetContextInfo(context, CL_CONTEXT_DEVICES, deviceBufferSize, devices,NULL);
if (errNum != CL_SUCCESS) {
delete [] devices;
std::cerr << "Failed to get device IDs";
return NULL;
}
commandQueue = clCreateCommandQueue(context, devices[0], 0, NULL);
if (commandQueue == NULL) {
delete [] devices;
std::cerr << "Failed to create commandQueue for device 0";
return NULL;
}
*device = devices[0];
delete [] devices;
return commandQueue;
}
cl_program CreateProgram(cl_context context, cl_device_id device, const char* fileName)
{
cl_int errNum;
cl_program program;
std::ifstream kernelFile(fileName, std::ios::in);
if (!kernelFile.is_open())
{
std::cerr << "Failed to open file for reading: " << fileName << std::endl;
return NULL;
}
std::ostringstream oss;
oss << kernelFile.rdbuf();
std::string srcStdStr = oss.str();
const char *srcStr = srcStdStr.c_str();
program = clCreateProgramWithSource(context, 1,
(const char**)&srcStr,
NULL, NULL);
if (program == NULL)
{
std::cerr << "Failed to create CL program from source." << std::endl;
return NULL;
}
errNum = clBuildProgram(program, 0, NULL, NULL, NULL, NULL);
if (errNum != CL_SUCCESS)
{
char buildLog[16384];
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,
sizeof(buildLog), buildLog, NULL);
std::cerr << "Error in kernel: " << std::endl;
std::cerr << buildLog;
clReleaseProgram(program);
return NULL;
}
return program;
}
bool CreateMemObjects(cl_context context, cl_mem memObjects[3],
float *a, float *b)
{
memObjects[0] = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(float) * ARRAY_SIZE, a, NULL);
memObjects[1] = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(float) * ARRAY_SIZE, b, NULL);
memObjects[2] = clCreateBuffer(context, CL_MEM_READ_WRITE,
sizeof(float) * ARRAY_SIZE, NULL, NULL);
if (memObjects[0] == NULL || memObjects[1] == NULL || memObjects[2] == NULL)
{
std::cerr << "Error creating memory objects." << std::endl;
return false;
}
return true;
}
void Cleanup(cl_context context, cl_command_queue commandQueue,
cl_program program, cl_kernel kernel, cl_mem memObjects[3])
{
for (int i = 0; i < 3; i++)
{
if (memObjects[i] != 0)
clReleaseMemObject(memObjects[i]);
}
if (commandQueue != 0)
clReleaseCommandQueue(commandQueue);
if (kernel != 0)
clReleaseKernel(kernel);
if (program != 0)
clReleaseProgram(program);
if (context != 0)
clReleaseContext(context);
}
int main(int argc, char** argv)
{
cl_context context = 0;
cl_command_queue commandQueue = 0;
cl_program program = 0;
cl_device_id device = 0;
cl_kernel kernel = 0;
cl_mem memObjects[3] = { 0, 0, 0 };
cl_int errNum;
// Create an OpenCL context on first available platform
context = CreateContext();
if (context == NULL)
{
std::cerr << "Failed to create OpenCL context." << std::endl;
return 1;
}
// Create a command-queue on the first device available
// on the created context
commandQueue = CreateCommandQueue(context, &device);
if (commandQueue == NULL)
{
Cleanup(context, commandQueue, program, kernel, memObjects);
return 1;
}
// Create OpenCL program from HelloWorld.cl kernel source
program = CreateProgram(context, device, "HelloWorld.cl");
if (program == NULL)
{
Cleanup(context, commandQueue, program, kernel, memObjects);
return 1;
}
// Create OpenCL kernel
kernel = clCreateKernel(program, "hello_kernel", NULL);
if (kernel == NULL)
{
std::cerr << "Failed to create kernel" << std::endl;
Cleanup(context, commandQueue, program, kernel, memObjects);
return 1;
}
// Create memory objects that will be used as arguments to
// kernel. First create host memory arrays that will be
// used to store the arguments to the kernel
float result[ARRAY_SIZE];
float a[ARRAY_SIZE];
float b[ARRAY_SIZE];
for (int i = 0; i < ARRAY_SIZE; i++)
{
a[i] = (float)i;
b[i] = (float)(i * 2);
}
if (!CreateMemObjects(context, memObjects, a, b))
{
Cleanup(context, commandQueue, program, kernel, memObjects);
return 1;
}
// Set the kernel arguments (result, a, b)
errNum = clSetKernelArg(kernel, 0, sizeof(cl_mem), &memObjects[0]);
errNum |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &memObjects[1]);
errNum |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &memObjects[2]);
if (errNum != CL_SUCCESS)
{
std::cerr << "Error setting kernel arguments." << std::endl;
Cleanup(context, commandQueue, program, kernel, memObjects);
return 1;
}
size_t globalWorkSize[1] = { ARRAY_SIZE };
size_t localWorkSize[1] = { 1 };
// Queue the kernel up for execution across the array
errNum = clEnqueueNDRangeKernel(commandQueue, kernel, 1, NULL,
globalWorkSize, localWorkSize,
0, NULL, NULL);
if (errNum != CL_SUCCESS)
{
std::cerr << "Error queuing kernel for execution." << std::endl;
Cleanup(context, commandQueue, program, kernel, memObjects);
return 1;
}
// Read the output buffer back to the Host
errNum = clEnqueueReadBuffer(commandQueue, memObjects[2], CL_TRUE,
0, ARRAY_SIZE * sizeof(float), result,
0, NULL, NULL);
if (errNum != CL_SUCCESS)
{
std::cerr << "Error reading result buffer." << std::endl;
Cleanup(context, commandQueue, program, kernel, memObjects);
return 1;
}
// Output the result buffer
for (int i = 0; i < ARRAY_SIZE; i++)
{
std::cout << result[i] << " ";
}
std::cout << std::endl;
std::cout << "Executed program succesfully." << std::endl;
Cleanup(context, commandQueue, program, kernel, memObjects);
return 0;
}
HelloWorld.cl :
__kernel void hello_kernel(
__global const float *a,
__global const float *b,
__global float *result)
{
int gid = get_global_id(0);
result[gid] = a[gid] + b[gid];
}
You just need to add one OpenCL include directory to the project and link to one libOpenCL. In my case (Ubuntu 13.04) I need to add /opt/intel/opencl-1.xxxx/include to the include paths of the project, which allow for the use of #include <CL/cl.h>.
Also add /opt/intel/opencl-1.xxxx/lib64/ to the linker search paths and add OpenCL to the link-libraries.
That should do it.

Resources