Esempio n. 1
0
PVideoFrame __stdcall TCPClient::GetFrame(int n, IScriptEnvironment* env) {

  int al_b = sizeof(ClientRequestFrame);
  ClientRequestFrame f;
  memset(&f, 0 , sizeof(ClientRequestFrame));
  f.n = n;

  bool ready = false;

  if (client->IsDataPending()) {
    client->GetReply();
    if (client->reply->last_reply_type == SERVER_SENDING_FRAME) {
      ServerFrameInfo* fi = (ServerFrameInfo *)client->reply->last_reply;
      if ((int)fi->framenumber == n) {
        ready = true;
        _RPT1(0, "TCPClient: Frame was PreRequested (hit!). Found frame %d.\n", n);
      }
    }
  }
  if (!ready) {
    _RPT1(0, "TCPClient: Frame was not PreRequested (miss). Requesting frame %d.\n", n);
    client->SendRequest(CLIENT_REQUEST_FRAME, &f, sizeof(ClientRequestFrame));
    client->GetReply();
  }

  PVideoFrame frame;
  int incoming_pitch;
  unsigned int incoming_bytes;

  if (client->reply->last_reply_type == SERVER_SENDING_FRAME) {
    ServerFrameInfo* fi = (ServerFrameInfo *)client->reply->last_reply;
    frame = env->NewVideoFrame(vi);

    if ((unsigned int)frame->GetRowSize() != fi->row_size)
      env->ThrowError("TCPClient: Internal Error - rowsize alignment was not correct.");
    if ((unsigned int)frame->GetHeight() != fi->height)
      env->ThrowError("TCPClient: Internal Error - height was not correct.");
    if (fi->framenumber != (unsigned int)n)
      env->ThrowError("TCPClient: Internal Error - framenumber was not correct.");

    incoming_pitch = fi->pitch;
    incoming_bytes = fi->data_size;

    BYTE* dstp = frame->GetWritePtr();
    BYTE* srcp = (unsigned char*)client->reply->last_reply + sizeof(ServerFrameInfo);
    TCPCompression* t = 0;

    switch (fi->compression) {
      case ServerFrameInfo::COMPRESSION_NONE:
          t = (TCPCompression*)new TCPCompression();        
        break;
      case ServerFrameInfo::COMPRESSION_DELTADOWN_LZO: {
          t = (TCPCompression*)new PredictDownLZO();
          break;
        }
      case ServerFrameInfo::COMPRESSION_DELTADOWN_HUFFMAN: {
          t = (TCPCompression*)new PredictDownHuffman();
          break;
                                                           }
      case ServerFrameInfo::COMPRESSION_DELTADOWN_GZIP: {
          t = (TCPCompression*)new PredictDownGZip();
          break;
        }
      default:
        env->ThrowError("TCPClient: Unknown compression.");
    }

    if (!vi.IsPlanar() || vi.IsY8()) {
      t->DeCompressImage(srcp, fi->row_size, fi->height, fi->pitch, fi->compressed_bytes);
      env->BitBlt(dstp, frame->GetPitch(), t->dst, incoming_pitch, frame->GetRowSize(), frame->GetHeight());
      if (!t->inplace) {
        _aligned_free(t->dst);
      }
      delete t;
    } else {
      // Y
      t->DeCompressImage(srcp, fi->row_size, fi->height, fi->pitch, fi->comp_Y_bytes);
      env->BitBlt(dstp, frame->GetPitch(), t->dst, incoming_pitch, frame->GetRowSize(), frame->GetHeight());
      if (!t->inplace) _aligned_free(t->dst);

      int uv_pitch = fi->pitchUV;
      int uv_rowsize  = fi->row_sizeUV;
      int uv_height = fi->heightUV;

      // U
      srcp += fi->comp_Y_bytes;
      t->DeCompressImage(srcp, uv_rowsize, uv_height, uv_pitch, fi->comp_U_bytes);
      env->BitBlt(frame->GetWritePtr(PLANAR_U), frame->GetPitch(PLANAR_U),
                  t->dst, uv_pitch, frame->GetRowSize(PLANAR_U), frame->GetHeight(PLANAR_U));
      if (!t->inplace) _aligned_free(t->dst);

      // V
      srcp += fi->comp_U_bytes;
      t->DeCompressImage(srcp, uv_rowsize, uv_height, uv_pitch, fi->comp_V_bytes);
      env->BitBlt(frame->GetWritePtr(PLANAR_V), frame->GetPitch(PLANAR_V),
                  t->dst, uv_pitch, frame->GetRowSize(PLANAR_V), frame->GetHeight(PLANAR_V));
      if (!t->inplace) _aligned_free(t->dst);
      delete t;
    }
  } else {
    if (client->reply->last_reply_type == INTERNAL_DISCONNECTED)
      env->ThrowError("TCPClient: Disconnected from server");

    env->ThrowError("TCPClient: Did not recieve expected packet (SERVER_SENDING_FRAME)");
  }

  if (true) {  // Request next frame
    f.n = n + 1;
    client->SendRequest(CLIENT_REQUEST_FRAME, &f, sizeof(ClientRequestFrame));
    _RPT1(0, "TCPClient: PreRequesting frame frame %d.\n", f.n);
  }

  return frame;
}
Esempio n. 2
0
static void btAlignedFreeDefault(void *ptr)
{
	_aligned_free(ptr);
}
Esempio n. 3
0
void  FrameAllocDestroy()
{
	_aligned_free( FrameAllocMemory[0] );
	_aligned_free( FrameAllocMemory[1] );
}
Esempio n. 4
0
int uv_fs_event_init(uv_loop_t* loop, uv_fs_event_t* handle,
    const char* filename, uv_fs_event_cb cb, int flags) {
  int name_size, is_path_dir;
  DWORD attr, last_error;
  wchar_t* dir = NULL, *dir_to_watch, *filenamew = NULL;
  wchar_t short_path[MAX_PATH];

  /* We don't support any flags yet. */
  assert(!flags);

  uv_fs_event_init_handle(loop, handle, filename, cb);

  /* Convert name to UTF16. */
  name_size = uv_utf8_to_utf16(filename, NULL, 0) * sizeof(wchar_t);
  filenamew = (wchar_t*)malloc(name_size);
  if (!filenamew) {
    uv_fatal_error(ERROR_OUTOFMEMORY, "malloc");
  }

  if (!uv_utf8_to_utf16(filename, filenamew, 
      name_size / sizeof(wchar_t))) {
    uv__set_sys_error(loop, GetLastError());
    return -1;
  }

  /* Determine whether filename is a file or a directory. */
  attr = GetFileAttributesW(filenamew);
  if (attr == INVALID_FILE_ATTRIBUTES) {
    last_error = GetLastError();
    goto error;
  }

  is_path_dir = (attr & FILE_ATTRIBUTE_DIRECTORY) ? 1 : 0;

  if (is_path_dir) {
     /* filename is a directory, so that's the directory that we will watch. */
    handle->dirw = filenamew;
    dir_to_watch = filenamew;
  } else {
    /* 
     * filename is a file.  So we split filename into dir & file parts, and
     * watch the dir directory.
     */
    
    /* Convert to short path. */
    if (!GetShortPathNameW(filenamew, short_path, COUNTOF(short_path))) {
      last_error = GetLastError();
      goto error;
    }

    if (uv_split_path(filenamew, &dir, &handle->filew) != 0) {
      last_error = GetLastError();
      goto error;
    }

    if (uv_split_path(short_path, NULL, &handle->short_filew) != 0) {
      last_error = GetLastError();
      goto error;
    }

    dir_to_watch = dir;
    free(filenamew);
    filenamew = NULL;
  }

  handle->dir_handle = CreateFileW(dir_to_watch,
                                   FILE_LIST_DIRECTORY,
                                   FILE_SHARE_READ | FILE_SHARE_DELETE |
                                     FILE_SHARE_WRITE,
                                   NULL,
                                   OPEN_EXISTING,
                                   FILE_FLAG_BACKUP_SEMANTICS |
                                     FILE_FLAG_OVERLAPPED,
                                   NULL);

  if (dir) {
    free(dir);
    dir = NULL;
  }

  if (handle->dir_handle == INVALID_HANDLE_VALUE) {
    last_error = GetLastError();
    goto error;
  }

  if (CreateIoCompletionPort(handle->dir_handle,
                             loop->iocp,
                             (ULONG_PTR)handle,
                             0) == NULL) {
    last_error = GetLastError();
    goto error;
  }

  handle->buffer = (char*)_aligned_malloc(uv_directory_watcher_buffer_size, 
    sizeof(DWORD));
  if (!handle->buffer) {
    uv_fatal_error(ERROR_OUTOFMEMORY, "malloc");
  }

  memset(&(handle->req.overlapped), 0, sizeof(handle->req.overlapped));

  if (!ReadDirectoryChangesW(handle->dir_handle,
                             handle->buffer,
                             uv_directory_watcher_buffer_size,
                             FALSE,
                             FILE_NOTIFY_CHANGE_FILE_NAME      |
                               FILE_NOTIFY_CHANGE_DIR_NAME     |
                               FILE_NOTIFY_CHANGE_ATTRIBUTES   |
                               FILE_NOTIFY_CHANGE_SIZE         |
                               FILE_NOTIFY_CHANGE_LAST_WRITE   |
                               FILE_NOTIFY_CHANGE_LAST_ACCESS  |
                               FILE_NOTIFY_CHANGE_CREATION     |
                               FILE_NOTIFY_CHANGE_SECURITY,
                             NULL,
                             &handle->req.overlapped,
                             NULL)) {
    last_error = GetLastError();
    goto error;
  }

  handle->req_pending = 1;
  return 0;

error:
  if (handle->filename) {
    free(handle->filename);
    handle->filename = NULL;
  }

  if (handle->filew) {
    free(handle->filew);
    handle->filew = NULL;
  }

  if (handle->short_filew) {
    free(handle->short_filew);
    handle->short_filew = NULL;
  }

  free(filenamew);

  if (handle->dir_handle != INVALID_HANDLE_VALUE) {
    CloseHandle(handle->dir_handle);
    handle->dir_handle = INVALID_HANDLE_VALUE;
  }

  if (handle->buffer) {
    _aligned_free(handle->buffer);
    handle->buffer = NULL;
  }

  uv__set_sys_error(loop, last_error);
  return -1;
}
Esempio n. 5
0
void coroutine_destroy(struct coroutine *co)
{
    _aligned_free(co);
}
Esempio n. 6
0
void __cdecl _aligned_free_dbg( void * memblock)
{
    _aligned_free(memblock);
}
void FutureMallocAllocator::Free(void * p)
{
	_aligned_free(p);
}
Esempio n. 8
0
File: shift.c Progetto: wittend/wdsp
void destroy_shift (SHIFT a)
{
	_aligned_free (a);
}
/**-----------------------------------------------------------------------------
 * 프로그램 시작점
 *------------------------------------------------------------------------------
 */
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR, INT )
{
    /// 윈도우 클래스 등록
    WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L,
                      GetModuleHandle(NULL), NULL, NULL, NULL, NULL,
                      "BasicFrame", NULL
                    };
    RegisterClassEx( &wc );

    /// 윈도우 생성
    HWND hWnd = CreateWindow( "BasicFrame", WINDOW_TITLE,
                              WS_OVERLAPPEDWINDOW, 100, 100, WINDOW_W, WINDOW_H,
                              GetDesktopWindow(), NULL, wc.hInstance, NULL );

    g_hwnd = hWnd;

    g_pLog = new ZFLog( ZF_LOG_TARGET_CONSOLE | ZF_LOG_TARGET_WINDOW );
    // g_pCamera = new ZCamera;
    g_pCamera = (ZCamera*)_aligned_malloc( sizeof( ZCamera ), 16 );

    /// Direct3D 초기화
    if( SUCCEEDED( InitD3D( hWnd ) ) )
    {
        if( SUCCEEDED( InitGeometry() ) )
        {

            /// 윈도우 출력
            ShowWindow( hWnd, SW_SHOWDEFAULT );
            UpdateWindow( hWnd );

            /// 메시지 루프
            MSG msg;
            ZeroMemory( &msg, sizeof(msg) );
            while( msg.message!=WM_QUIT )
            {
                /// 메시지큐에 메시지가 있으면 메시지 처리
                if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) )
                {
                    TranslateMessage( &msg );
                    DispatchMessage( &msg );
                }
                else
                {
                    /// 처리할 메시지가 없으면 Render()함수 호출
                    Render();
                }
            }
        }
    }

    delete g_pLog;
    // delete g_pCamera;
    if ( g_pCamera )
    {
        g_pCamera->~ZCamera();
        _aligned_free( g_pCamera );
    }

    /// 등록된 클래스 소거
    UnregisterClass( "D3D Tutorial", wc.hInstance );
    return 0;
}
static int test_progressive_ms_sample(char* ms_sample_path)
{
	int i, j, k;
	int count;
	int status;
	EGFX_SAMPLE_FILE files[3][4][4];
	EGFX_SAMPLE_FILE bitmaps[3][4][4];
	PROGRESSIVE_CONTEXT* progressive;
	g_Width = 1920;
	g_Height = 1080;
	g_DstStep = g_Width * 4;
	ZeroMemory(files, sizeof(files));
	ZeroMemory(bitmaps, sizeof(bitmaps));
	status = test_progressive_load_files(ms_sample_path, files);

	if (status < 0)
	{
		for (i = 0; i < 3; i++)
		{
			for (j = 0; j < 4; j++)
			{
				for (k = 0; k < 4; k++)
					sample_file_free(&files[i][j][k]);
			}
		}

		return -1;
	}

	status = test_progressive_load_bitmaps(ms_sample_path, bitmaps);

	if (status < 0)
	{
		for (i = 0; i < 3; i++)
		{
			for (j = 0; j < 4; j++)
			{
				for (k = 0; k < 4; k++)
					sample_file_free(&files[i][j][k]);
			}
		}

		return -1;
	}

	count = 4;
	progressive = progressive_context_new(FALSE);
	g_DstData = _aligned_malloc(g_DstStep * g_Height, 16);
	progressive_create_surface_context(progressive, 0, g_Width, g_Height);

	/* image 1 */

	if (1)
	{
		printf("\nSample Image 1\n");
		test_image_fill(g_DstData, g_DstStep, 0, 0, g_Width, g_Height, 0xFF000000);
		test_progressive_decode(progressive, files[0][0], bitmaps[0][0], 0, count);
		test_progressive_decode(progressive, files[0][1], bitmaps[0][1], 1, count);
		test_progressive_decode(progressive, files[0][2], bitmaps[0][2], 2, count);
		test_progressive_decode(progressive, files[0][3], bitmaps[0][3], 3, count);
	}

	/* image 2 */

	if (0)
	{
		printf("\nSample Image 2\n"); /* sample data is in incorrect order */
		test_image_fill(g_DstData, g_DstStep, 0, 0, g_Width, g_Height, 0xFF000000);
		test_progressive_decode(progressive, files[1][0], bitmaps[1][0], 0, count);
		test_progressive_decode(progressive, files[1][1], bitmaps[1][1], 1, count);
		test_progressive_decode(progressive, files[1][2], bitmaps[1][2], 2, count);
		test_progressive_decode(progressive, files[1][3], bitmaps[1][3], 3, count);
	}

	/* image 3 */

	if (0)
	{
		printf("\nSample Image 3\n"); /* sample data is in incorrect order */
		test_image_fill(g_DstData, g_DstStep, 0, 0, g_Width, g_Height, 0xFF000000);
		test_progressive_decode(progressive, files[2][0], bitmaps[2][0], 0, count);
		test_progressive_decode(progressive, files[2][1], bitmaps[2][1], 1, count);
		test_progressive_decode(progressive, files[2][2], bitmaps[2][2], 2, count);
		test_progressive_decode(progressive, files[2][3], bitmaps[2][3], 3, count);
	}

	progressive_context_free(progressive);

	for (i = 0; i < 3; i++)
	{
		for (j = 0; j < 4; j++)
		{
			for (k = 0; k < 4; k++)
			{
				sample_file_free(&bitmaps[i][j][k]);
				sample_file_free(&files[i][j][k]);
			}
		}
	}

	_aligned_free(g_DstData);
	return 0;
}
	~WriteBuffer() 
	{
		_aligned_free(ptr_);
	}
DWORD WINAPI RandomThreadProc(LPVOID lpParameter) 
{
	const int buffer_element_count = 30000;
	const int max_float_digits = 8;

	sfmt_t sfmt;
	sfmt_init_gen_rand(&sfmt, GetCurrentThreadId());
	uint32_t* randoms = (uint32_t*) _aligned_malloc(sizeof(uint32_t)*buffer_element_count, 64);

	bool done = false;

	WriteBuffer* write_buffer = new WriteBuffer(buffer_element_count, max_float_digits);
	// std::ofstream output();
	while (!done) 
	{
		// Prepare a block of numbers for writing.
		char* write_ptr = write_buffer->ptr_;

		sfmt_fill_array32(&sfmt, randoms, buffer_element_count);

		*(write_ptr++) = '0';
		*(write_ptr++) = '.';

		// Compute digits
		for (int k = 0; k < buffer_element_count; ++k)
		{
			// Format each float to string and append to buffer.
			// float random = float(rand()) / RAND_MAX;
			// float random = float(randoms[k]) / 4294967296.0f;
			// int fractional_part = random *  1000000000;
			// this turns the fractional part of the float back into usable integer.
#if 1
			float f1 = float(randoms[k]) / 429496.7296f;
			int d1 = int(f1);
			float f2 = (f1 - d1)*10000.0f;
			int d2 = int(f2 + 0.5f);
#else
			double f1 = double(randoms[k]) / 429496.7296;
			int d1 = int(f1);
			double f2 = (f1 - d1)*10000.0;
			int d2 = int(f2 + 0.5);
#endif
			// convert to string form.
			// we use a lookup table for this.
			uint32_t part_1 = *((uint32_t*)(g_x + d1));
			*((uint32_t*)(write_ptr)) = part_1;

			uint32_t part_2 = *((uint32_t*)(g_x + d2));
			*((int*)(write_ptr + 4)) = part_2;

			*((int*)(write_ptr + 8)) = '.0\n\r'; // order of chars reversed.
#ifdef _DEBUG
			printf("%.8lf => %s\n", double(randoms[k]) / 4294967296.0, write_ptr-2);
#endif
			write_ptr+=12;
		}
		// get rid of last 0.
		write_ptr-=2;
		// Compute how many bytes to write.
		write_buffer->useful_data_size_ =  write_ptr - write_buffer->ptr_;

		// Enqueue for writing.
		// while (write_buffer) {
			EnterCriticalSection(&g_write_queue_cs);
			/*if (g_write_queue.size() < kMaxQueue) 
			{
				g_write_queue.push(write_buffer);
				SetEvent(g_write_queue_has_more_data_event);
				write_buffer = NULL;
			} else 
			{
				// ops.
		    }*/
			g_total_bytes_written += write_buffer->useful_data_size_;
			done = g_done;
			if (done) 
			{
				DWORD bytes_written = 0;
				::WriteFile(g_hFile, write_buffer->ptr_, write_buffer->useful_data_size_, 
					&bytes_written, NULL);
			}
			LeaveCriticalSection(&g_write_queue_cs);
			/* if (write_buffer) {
				// slow down writing, queue is full
				// printf("S");
				WaitForSingleObject(g_write_queue_accepts_more_data_event, 10);
			}*/
		// }
	}

	_aligned_free(randoms);

	return 0;
}
    /**
     * Destructor
     */
    ~MonteCarloAsian()
    {
        if(sigma)
        {
            free(sigma);
            sigma = NULL;
        }

        if(price) 
        {
            free(price);
            price = NULL;
        }

        if(vega) 
        {
            free(vega);
            vega = NULL;
        }

        if(refPrice) 
        {
            free(refPrice);
            refPrice = NULL;
        }

        if(refVega) 
        {
            free(refVega);
            refVega = NULL;
        }

        if(randNum)
        {
            #ifdef _WIN32
                _aligned_free(randNum);
            #else
                free(randNum);
            #endif
            randNum = NULL;
        }

        if(priceVals) 
        {
            free(priceVals);
            priceVals = NULL;
        }

        if(priceDeriv)
        {
            free(priceDeriv);
            priceDeriv = NULL;
        }

        if(devices)
        {
            free(devices);
            devices = NULL;
        }

        if(maxWorkItemSizes)
        {
            free(maxWorkItemSizes);
            maxWorkItemSizes = NULL;
        }
    }
Esempio n. 14
0
PlanarFrame::~PlanarFrame()
{
	if (y != NULL) { _aligned_free(y); y = NULL; }
	if (u != NULL) { _aligned_free(u); u = NULL; }
	if (v != NULL) { _aligned_free(v); v = NULL; }
}
Esempio n. 15
0
static void platformAlignedFree(void* ptr)
{
	_aligned_free(ptr);
}
Esempio n. 16
0
/*********************************************************************
 *		_aligned_offset_realloc (MSVCRT.@)
 */
void * CDECL _aligned_offset_realloc(void *memblock, size_t size,
                                     size_t alignment, size_t offset)
{
    void * temp, **saved;
    size_t old_padding, new_padding, old_size;
    TRACE("(%p, %lu, %lu, %lu)\n", memblock, size, alignment, offset);

    if (!memblock)
        return _aligned_offset_malloc(size, alignment, offset);

    /* alignment must be a power of 2 */
    if ((alignment & (alignment - 1)) != 0)
    {
        *_errno() = EINVAL;
        return NULL;
    }

    /* offset must be less than size */
    if (offset >= size)
    {
        *_errno() = EINVAL;
        return NULL;
    }

    if (size == 0)
    {
        _aligned_free(memblock);
        return NULL;
    }

    /* don't align to less than void pointer size */
    if (alignment < sizeof(void *))
        alignment = sizeof(void *);

    /* make sure alignment and offset didn't change */
    saved = SAVED_PTR(memblock);
    if (memblock != ALIGN_PTR(*saved, alignment, offset))
    {
        *_errno() = EINVAL;
        return NULL;
    }

    old_padding = (char *)memblock - (char *)*saved;

    /* Get previous size of block */
    old_size = _msize(*saved);
    if (old_size == -1)
    {
        /* It seems this function was called with an invalid pointer. Bail out. */
        return NULL;
    }

    /* Adjust old_size to get amount of actual data in old block. */
    if (old_size < old_padding)
    {
        /* Shouldn't happen. Something's weird, so bail out. */
        return NULL;
    }
    old_size -= old_padding;

    temp = realloc(*saved, size + alignment + sizeof(void *));

    if (!temp)
        return NULL;

    /* adjust pointer for proper alignment and offset */
    memblock = ALIGN_PTR(temp, alignment, offset);

    /* Save the real allocation address below returned address */
    /* so it can be found later to free. */
    saved = SAVED_PTR(memblock);

    new_padding = (char *)memblock - (char *)temp;

/*
   Memory layout of old block is as follows:
   +-------+---------------------+-+--------------------------+-----------+
   |  ...  | "old_padding" bytes | | ... "old_size" bytes ... |    ...    |
   +-------+---------------------+-+--------------------------+-----------+
           ^                     ^ ^
           |                     | |
        *saved               saved memblock

   Memory layout of new block is as follows:
   +-------+-----------------------------+-+----------------------+-------+
   |  ...  |    "new_padding" bytes      | | ... "size" bytes ... |  ...  |
   +-------+-----------------------------+-+----------------------+-------+
           ^                             ^ ^
           |                             | |
          temp                       saved memblock

   However, in the new block, actual data is still written as follows
   (because it was copied by MSVCRT_realloc):
   +-------+---------------------+--------------------------------+-------+
   |  ...  | "old_padding" bytes |   ... "old_size" bytes ...     |  ...  |
   +-------+---------------------+--------------------------------+-------+
           ^                             ^ ^
           |                             | |
          temp                       saved memblock

   Therefore, min(old_size,size) bytes of actual data have to be moved
   from the offset they were at in the old block (temp + old_padding),
   to the offset they have to be in the new block (temp + new_padding == memblock).
*/
    if (new_padding != old_padding)
        memmove((char *)memblock, (char *)temp + old_padding, (old_size < size) ? old_size : size);

    *saved = temp;

    return memblock;
}
Esempio n. 17
0
/*
 * util_aligned_free -- free allocated memory in util_aligned_malloc
 */
void
util_aligned_free(void *ptr)
{
	_aligned_free(ptr);
}
Esempio n. 18
0
void FreeImage_Aligned_Free(void* mem) {
	_aligned_free(mem);
}
Esempio n. 19
0
void destroy_compressor (COMPRESSOR a)
{
	_aligned_free (a);
}
SceneManager::~SceneManager() {
	_aligned_free(m_frame);
	_aligned_free(m_object);
};
float actual_main(int argc, TCHAR* argv[], int DIMENSION){
    cl_int err;
    ocl_args_d_t ocl;
    cl_device_type deviceType = CL_DEVICE_TYPE_GPU;

    LARGE_INTEGER perfFrequency;
    LARGE_INTEGER performanceCountNDRangeStart;
    LARGE_INTEGER performanceCountNDRangeStop;

	
    cl_uint arrayWidth  = DIMENSION;
    cl_uint arrayHeight = DIMENSION;

    //initialize Open CL objects (context, queue, etc.)
    if (CL_SUCCESS != SetupOpenCL(&ocl, deviceType))
    {
        return -1;
    }

    // allocate working buffers. 
    // the buffer should be aligned with 4K page and size should fit 64-byte cached line
    cl_uint optimizedSize = ((sizeof(cl_int) * arrayWidth * arrayHeight - 1)/64 + 1) * 64;
    cl_int* inputA  = (cl_int*)_aligned_malloc(optimizedSize, 4096);
    cl_int* inputB  = (cl_int*)_aligned_malloc(optimizedSize, 4096);
    cl_int* outputC = (cl_int*)_aligned_malloc(optimizedSize, 4096);
    if (NULL == inputA || NULL == inputB || NULL == outputC)
    {
        LogError("Error: _aligned_malloc failed to allocate buffers.\n");
        return -1;
    }

    //random input
    generateInput(inputA, arrayWidth, arrayHeight);
    generateInput(inputB, arrayWidth, arrayHeight);

    // Create OpenCL buffers from host memory
    // These buffers will be used later by the OpenCL kernel
    if (CL_SUCCESS != CreateBufferArguments(&ocl, inputA, inputB, outputC, arrayWidth, arrayHeight))
    {
        return -1;
    }

     // Create and build the OpenCL program
    if (CL_SUCCESS != CreateAndBuildProgram(&ocl))
    {
        return -1;
    }

    // Program consists of kernels.
    // Each kernel can be called (enqueued) from the host part of OpenCL application.
    // To call the kernel, you need to create it from existing program.
    ocl.kernel = clCreateKernel(ocl.program, "Mul", &err);
    if (CL_SUCCESS != err)
    {
        LogError("Error: clCreateKernel returned %s\n", TranslateOpenCLError(err));
        return -1;
    }

    // Passing arguments into OpenCL kernel.
    if (CL_SUCCESS != SetKernelArguments(&ocl))
    {
        return -1;
    }

    // Regularly you wish to use OpenCL in your application to achieve greater performance results
    // that are hard to achieve in other ways.
    // To understand those performance benefits you may want to measure time your application spent in OpenCL kernel execution.
    // The recommended way to obtain this time is to measure interval between two moments:
    //   - just before clEnqueueNDRangeKernel is called, and
    //   - just after clFinish is called
    // clFinish is necessary to measure entire time spending in the kernel, measuring just clEnqueueNDRangeKernel is not enough,
    // because this call doesn't guarantees that kernel is finished.
    // clEnqueueNDRangeKernel is just enqueue new command in OpenCL command queue and doesn't wait until it ends.
    // clFinish waits until all commands in command queue are finished, that suits your need to measure time.
    bool queueProfilingEnable = true;
    if (queueProfilingEnable)
        QueryPerformanceCounter(&performanceCountNDRangeStart);
    // Execute (enqueue) the kernel
    if (CL_SUCCESS != ExecuteAddKernel(&ocl, arrayWidth, arrayHeight))
    {
        return -1;
    }
    if (queueProfilingEnable)
        QueryPerformanceCounter(&performanceCountNDRangeStop);

    // The last part of this function: getting processed results back.
    // use map-unmap sequence to update original memory area with output buffer.
    ReadAndVerify(&ocl, arrayWidth, arrayHeight, inputA, inputB);

    // retrieve performance counter frequency
    if (queueProfilingEnable)
    {
        QueryPerformanceFrequency(&perfFrequency);
        //LogInfo("NDRange performance counter time %f ms.\n",
          //  1000.0f*(float)(performanceCountNDRangeStop.QuadPart - performanceCountNDRangeStart.QuadPart) / (float)perfFrequency.QuadPart);
    }

    _aligned_free(inputA);
    _aligned_free(inputB);
    _aligned_free(outputC);

	return 1e6*(float)(performanceCountNDRangeStop.QuadPart - performanceCountNDRangeStart.QuadPart) / (float)perfFrequency.QuadPart;
}
Esempio n. 22
0
void xf_window_free(xfContext* xfc)
{
	if (xfc->gc_mono)
	{
		XFreeGC(xfc->display, xfc->gc_mono);
		xfc->gc_mono = 0;
	}

	if (xfc->window)
	{
		xf_DestroyDesktopWindow(xfc, xfc->window);
		xfc->window = NULL;
	}

	if (xfc->hdc)
	{
		gdi_DeleteDC(xfc->hdc);
		xfc->hdc = NULL;
	}

	if (xfc->xv_context)
	{
		xf_tsmf_uninit(xfc, NULL);
		xfc->xv_context = NULL;
	}

	if (xfc->bitmap_buffer)
	{
		_aligned_free(xfc->bitmap_buffer);
		xfc->bitmap_buffer = NULL;
		xfc->bitmap_size = 0;
	}

	if (xfc->image)
	{
		xfc->image->data = NULL;
		XDestroyImage(xfc->image);
		xfc->image = NULL;
	}

	if (xfc->bitmap_mono)
	{
		XFreePixmap(xfc->display, xfc->bitmap_mono);
		xfc->bitmap_mono = 0;
	}

	if (xfc->primary)
	{
		XFreePixmap(xfc->display, xfc->primary);
		xfc->primary = 0;
	}

	if (xfc->gc)
	{
		XFreeGC(xfc->display, xfc->gc);
		xfc->gc = 0;
	}

	if (xfc->modifierMap)
	{
		XFreeModifiermap(xfc->modifierMap);
		xfc->modifierMap = NULL;
	}
}
Esempio n. 23
0
static BOOL gdi_mem3blt(rdpContext* context, MEM3BLT_ORDER* mem3blt)
{
	BYTE* data;
	rdpBrush* brush;
	UINT32 foreColor;
	UINT32 backColor;
	gdiBitmap* bitmap;
	GDI_COLOR originalColor;
	HGDI_BRUSH originalBrush;
	rdpGdi* gdi = context->gdi;
	BOOL ret = TRUE;

	brush = &mem3blt->brush;
	bitmap = (gdiBitmap*) mem3blt->bitmap;

	foreColor = freerdp_convert_gdi_order_color(mem3blt->foreColor, gdi->srcBpp, gdi->format, gdi->palette);
	backColor = freerdp_convert_gdi_order_color(mem3blt->backColor, gdi->srcBpp, gdi->format, gdi->palette);

	originalColor = gdi_SetTextColor(gdi->drawing->hdc, foreColor);

	if (brush->style == GDI_BS_SOLID)
	{
		originalBrush = gdi->drawing->hdc->brush;
		gdi->drawing->hdc->brush = gdi_CreateSolidBrush(foreColor);
		if (!gdi->drawing->hdc->brush)
		{
			ret = FALSE;
			goto out_fail;
		}

		gdi_BitBlt(gdi->drawing->hdc, mem3blt->nLeftRect, mem3blt->nTopRect,
				mem3blt->nWidth, mem3blt->nHeight, bitmap->hdc,
				mem3blt->nXSrc, mem3blt->nYSrc, gdi_rop3_code(mem3blt->bRop));

		gdi_DeleteObject((HGDIOBJECT) gdi->drawing->hdc->brush);
		gdi->drawing->hdc->brush = originalBrush;
	}
	else if (brush->style == GDI_BS_PATTERN)
	{
		HGDI_BITMAP hBmp;
		UINT32 brushFormat;

		if (brush->bpp > 1)
		{
			brushFormat = gdi_get_pixel_format(brush->bpp, FALSE);

			data = (BYTE*) _aligned_malloc(8 * 8 * gdi->bytesPerPixel, 16);
			if (!data)
			{
				ret = FALSE;
				goto out_fail;
			}

			freerdp_image_copy(data, gdi->format, -1, 0, 0,
					8, 8, brush->data, brushFormat, -1, 0, 0, gdi->palette);
		}
		else
		{
			data = (BYTE*) _aligned_malloc(8 * 8 * gdi->bytesPerPixel, 16);
			if (!data)
			{
				ret = FALSE;
				goto out_fail;
			}

			freerdp_image_copy_from_monochrome(data, gdi->format, -1, 0, 0, 8, 8,
					brush->data, backColor, foreColor, gdi->palette);
		}

		hBmp = gdi_CreateBitmap(8, 8, gdi->drawing->hdc->bitsPerPixel, data);
		if (!hBmp)
		{
			_aligned_free(data);
			ret = FALSE;
			goto out_fail;
		}

		originalBrush = gdi->drawing->hdc->brush;
		gdi->drawing->hdc->brush = gdi_CreatePatternBrush(hBmp);
		if (!gdi->drawing->hdc->brush)
		{
			gdi_DeleteObject((HGDIOBJECT) hBmp);
			goto out_fail;
		}
		gdi->drawing->hdc->brush->nXOrg = brush->x;
		gdi->drawing->hdc->brush->nYOrg = brush->y;

		gdi_BitBlt(gdi->drawing->hdc, mem3blt->nLeftRect, mem3blt->nTopRect,
				mem3blt->nWidth, mem3blt->nHeight, bitmap->hdc,
				mem3blt->nXSrc, mem3blt->nYSrc, gdi_rop3_code(mem3blt->bRop));

		gdi_DeleteObject((HGDIOBJECT) gdi->drawing->hdc->brush);
		gdi->drawing->hdc->brush = originalBrush;
	}
	else
	{
		WLog_ERR(TAG,  "Mem3Blt unimplemented brush style:%d", brush->style);
	}

out_fail:
	gdi_SetTextColor(gdi->drawing->hdc, originalColor);
	return ret;
}
void ReleaseApe1(void* addr, size_t size) {
  assert(addr != NULL && size != 0);
  _aligned_free(addr);
}
Esempio n. 25
0
OMX_ERRORTYPE COMXCoreComponent::AllocOutputBuffers(bool use_buffers /* = false */)
{
  OMX_ERRORTYPE omx_err = OMX_ErrorNone;

  if(!m_handle)
    return OMX_ErrorUndefined;

  m_omx_output_use_buffers = use_buffers; 

  OMX_PARAM_PORTDEFINITIONTYPE portFormat;
  OMX_INIT_STRUCTURE(portFormat);
  portFormat.nPortIndex = m_output_port;

  omx_err = OMX_GetParameter(m_handle, OMX_IndexParamPortDefinition, &portFormat);
  if(omx_err != OMX_ErrorNone)
    return omx_err;

  if(GetState() != OMX_StateIdle)
  {
    if(GetState() != OMX_StateLoaded)
      SetStateForComponent(OMX_StateLoaded);

    SetStateForComponent(OMX_StateIdle);
  }

  omx_err = EnablePort(m_output_port, false);
  if(omx_err != OMX_ErrorNone)
    return omx_err;

  m_output_alignment     = portFormat.nBufferAlignment;
  m_output_buffer_count  = portFormat.nBufferCountActual;
  m_output_buffer_size   = portFormat.nBufferSize;

  CLog::Log(LOGDEBUG, "COMXCoreComponent::AllocOutputBuffers component(%s) - port(%d), nBufferCountMin(%u), nBufferCountActual(%u), nBufferSize(%u) nBufferAlignmen(%u)\n",
            m_componentName.c_str(), m_output_port, portFormat.nBufferCountMin,
            portFormat.nBufferCountActual, portFormat.nBufferSize, portFormat.nBufferAlignment);

  for (size_t i = 0; i < portFormat.nBufferCountActual; i++)
  {
    OMX_BUFFERHEADERTYPE *buffer = NULL;
    OMX_U8* data = NULL;

    if(m_omx_output_use_buffers)
    {
      data = (OMX_U8*)_aligned_malloc(portFormat.nBufferSize, m_output_alignment);
      omx_err = OMX_UseBuffer(m_handle, &buffer, m_output_port, NULL, portFormat.nBufferSize, data);
    }
    else
    {
      omx_err = OMX_AllocateBuffer(m_handle, &buffer, m_output_port, NULL, portFormat.nBufferSize);
    }
    if(omx_err != OMX_ErrorNone)
    {
      CLog::Log(LOGERROR, "COMXCoreComponent::AllocOutputBuffers component(%s) - OMX_UseBuffer failed with omx_err(0x%x)\n",
        m_componentName.c_str(), omx_err);

      if(m_omx_output_use_buffers && data)
       _aligned_free(data);

      return omx_err;
    }
    buffer->nOutputPortIndex = m_output_port;
    buffer->nFilledLen       = 0;
    buffer->nOffset          = 0;
    buffer->pAppPrivate      = (void*)i;
    m_omx_output_buffers.push_back(buffer);
    m_omx_output_available.push(buffer);
  }

  omx_err = WaitForCommand(OMX_CommandPortEnable, m_output_port);

  m_flush_output = false;

  return omx_err;
}
Esempio n. 26
0
/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
UINT printer_register(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints,
                      rdpPrinter* printer)
{
	char* port;
	UINT32 Flags;
	int DriverNameLen;
	WCHAR* DriverName = NULL;
	int PrintNameLen;
	WCHAR* PrintName = NULL;
	UINT32 CachedFieldsLen;
	BYTE* CachedPrinterConfigData;
	PRINTER_DEVICE* printer_dev;
	UINT error;
	port = malloc(10);

	if (!port)
	{
		WLog_ERR(TAG, "malloc failed!");
		return CHANNEL_RC_NO_MEMORY;
	}

	sprintf_s(port, 10, "PRN%d", printer->id);
	printer_dev = (PRINTER_DEVICE*) calloc(1, sizeof(PRINTER_DEVICE));

	if (!printer_dev)
	{
		WLog_ERR(TAG, "calloc failed!");
		free(port);
		return CHANNEL_RC_NO_MEMORY;
	}

	printer_dev->device.type = RDPDR_DTYP_PRINT;
	printer_dev->device.name = port;
	printer_dev->device.IRPRequest = printer_irp_request;
	printer_dev->device.Free = printer_free;
	printer_dev->rdpcontext = pEntryPoints->rdpcontext;
	printer_dev->printer = printer;
	CachedFieldsLen = 0;
	CachedPrinterConfigData = NULL;
	Flags = 0;

	if (printer->is_default)
		Flags |= RDPDR_PRINTER_ANNOUNCE_FLAG_DEFAULTPRINTER;

	DriverNameLen = ConvertToUnicode(CP_UTF8, 0, printer->driver, -1, &DriverName,
	                                 0) * 2;
	PrintNameLen = ConvertToUnicode(CP_UTF8, 0, printer->name, -1, &PrintName,
	                                0) * 2;
	printer_dev->device.data = Stream_New(NULL,
	                                      28 + DriverNameLen + PrintNameLen + CachedFieldsLen);

	if (!printer_dev->device.data)
	{
		WLog_ERR(TAG, "calloc failed!");
		error = CHANNEL_RC_NO_MEMORY;
		free(DriverName);
		free(PrintName);
		goto error_out;
	}

	Stream_Write_UINT32(printer_dev->device.data, Flags);
	Stream_Write_UINT32(printer_dev->device.data, 0); /* CodePage, reserved */
	Stream_Write_UINT32(printer_dev->device.data, 0); /* PnPNameLen */
	Stream_Write_UINT32(printer_dev->device.data, DriverNameLen + 2);
	Stream_Write_UINT32(printer_dev->device.data, PrintNameLen + 2);
	Stream_Write_UINT32(printer_dev->device.data, CachedFieldsLen);
	Stream_Write(printer_dev->device.data, DriverName, DriverNameLen);
	Stream_Write_UINT16(printer_dev->device.data, 0);
	Stream_Write(printer_dev->device.data, PrintName, PrintNameLen);
	Stream_Write_UINT16(printer_dev->device.data, 0);

	if (CachedFieldsLen > 0)
	{
		Stream_Write(printer_dev->device.data, CachedPrinterConfigData,
		             CachedFieldsLen);
	}

	free(DriverName);
	free(PrintName);
	printer_dev->pIrpList = (WINPR_PSLIST_HEADER) _aligned_malloc(sizeof(
	                            WINPR_SLIST_HEADER), MEMORY_ALLOCATION_ALIGNMENT);

	if (!printer_dev->pIrpList)
	{
		WLog_ERR(TAG, "_aligned_malloc failed!");
		error = CHANNEL_RC_NO_MEMORY;
		goto error_out;
	}

	InitializeSListHead(printer_dev->pIrpList);

	if (!(printer_dev->event = CreateEvent(NULL, TRUE, FALSE, NULL)))
	{
		WLog_ERR(TAG, "CreateEvent failed!");
		error = ERROR_INTERNAL_ERROR;
		goto error_out;
	}

	if (!(printer_dev->stopEvent = CreateEvent(NULL, TRUE, FALSE, NULL)))
	{
		WLog_ERR(TAG, "CreateEvent failed!");
		error = ERROR_INTERNAL_ERROR;
		goto error_out;
	}

	if ((error = pEntryPoints->RegisterDevice(pEntryPoints->devman,
	             (DEVICE*) printer_dev)))
	{
		WLog_ERR(TAG, "RegisterDevice failed with error %"PRIu32"!", error);
		goto error_out;
	}

	if (!(printer_dev->thread = CreateThread(NULL, 0,
	                            (LPTHREAD_START_ROUTINE) printer_thread_func, (void*) printer_dev, 0, NULL)))
	{
		WLog_ERR(TAG, "CreateThread failed!");
		error = ERROR_INTERNAL_ERROR;
		goto error_out;
	}

	return CHANNEL_RC_OK;
error_out:
	CloseHandle(printer_dev->stopEvent);
	CloseHandle(printer_dev->event);
	_aligned_free(printer_dev->pIrpList);
	Stream_Free(printer_dev->device.data, TRUE);
	free(printer_dev);
	free(port);
	return error;
}
Esempio n. 27
0
void mpeg2_free(void *mem_ptr)
{
 _aligned_free(mem_ptr);
}
SceneManager::~SceneManager() 
{
	_aligned_free(mFrame);
	_aligned_free(mObject);
};
Esempio n. 29
0
void CTsPacket::Free(void *pBuffer)
{
	_aligned_free(pBuffer);
}